Click here to Skip to main content
Licence CPOL
First Posted 5 Apr 2004
Views 88,070
Downloads 1,006
Bookmarked 59 times

Ordering Items in the Property Grid

By | 5 Apr 2004 | Article
A simple custom attribute to order properties in the PropertyGrid.

Sample screenshot

Introduction

The PropertyGrid Component that ships with Visual Studio is a great way to add configurability to an application with very little effort. An object's properties are displayed when the object is assigned to the grid's SelectedObject property. The properties are displayed in either alphabetic order, or in categorized alphabetic order. Unfortunately, there is no built-in functionality to specify any other order. This article presents some simple code which allows the order of properties to be specified via a custom attribute in the same form as the grid's other attributes.

Using the code

Properties in code can be decorated with attributes to group them in categories when shown in the Property Grid. Descriptions can be applied in a similar way. The attributes are extracted via reflection when the object is assigned to the grid.

For example, using the following code -

[DefaultProperty("Name")]
public class Person
{
    protected const string PERSONAL_CAT = "Personal Details";
    
    private string _name = "Bob";
    private DateTime _birthday = new DateTime(1975,1,1);

    [Category(PERSONAL_CAT)]
    public string Name
    {
        get {return _name;} 
        set {_name = value;} 
    }

    [Category(PERSONAL_CAT)]
    public DateTime Birthday
    {
        get {return _birthday;}
        set {_birthday = value;}
    }

    [Category(PERSONAL_CAT)]
    public int Age
    {
        get 
        {
            TimeSpan age = DateTime.Now - _birthday; 
            return (int)age.TotalDays / 365; 
        }
    }
}

an instantiated object assigned to the PropertyGrid will look like this -

Sample screenshot

The name, birthday and age are shown in the "Personal Details" category as expected. The name and birthday are editable as they have gets & sets. The age is read-only. The name is highlighted as the default property. This is fine in development, but a client is unlikely to want the key piece of information, i.e. the name, coming last due to the alphabetic order. The alphabetic ordering will also be applied to the combined properties in objects derived from the Person class. Ideally, we want the ordering to be- 'name', then 'birthday', then 'age'. Any additional properties added in derived classes should follow from these, or be placed in another category.

Enter the Property Sorter. With some additional attributes, and the inclusion of the PropertySorter.cs file in the project, the ordering can be defined. The Person class is modified to look like this -

[TypeConverter(typeof(PropertySorter))]
[DefaultProperty("Name")]
public class Person
{
    protected const string PERSONAL_CAT = "Personal Details";
    
    private string _name = "Bob";
    private DateTime _birthday = new DateTime(1975,1,1);

    [Category(PERSONAL_CAT), PropertyOrder(10)]
    public string Name
    {
        get {return _name;} 
        set {_name = value;} 
    }

    [Category(PERSONAL_CAT), PropertyOrder(11)]
    public DateTime Birthday
    {
        get {return _birthday;}
        set {_birthday = value;}
    }

    [Category(PERSONAL_CAT), PropertyOrder(12)]
    public int Age
    {
        get 
        {
            TimeSpan age = DateTime.Now - _birthday; 
            return (int)age.TotalDays / 365; 
        }
    }
}

The only changes are the addition of the TypeConverter attribute at the top, and the PropertyOrder attributes on each property. When the class is instantiated and assigned to the PropertyGrid, it looks like this -

Person Class Ordered

Furthermore, any derived classes can have PropertyOrder attributes assigned and they will be honored. The order value passed in the attribute signifies the rank of the property in a sparse array (i.e. non-contiguous). Categories can be added on 'hundreds' boundaries (100, 200, 300 etc.) to allow subsequent categories to be added without breaking previous code. (Doesn't that remind you of line numbers in Basic?)

Points of Interest

The code to do the ordering is very simple, and not really worth describing. Have a look at PropertySorter.cs to see how it works. I did like the use of dynamic code compilation in the demo project to dynamically compile the examples, and allow you to change and test them immediately (go on try it!). Maybe, this will result in another CP project for a CP demo harness?

Conclusion

This is some very simple code to fix a hole in PropertyGrid's armory. Being able to specify the order of properties using attributes makes your data look better. The demo application provides some code samples that are dynamically compiled, so you can change the code and see the effects immediately. I hope someone finds this useful!

History

First CP project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Paul Tingey

Software Developer (Senior)

New Zealand New Zealand

Member

Working with code since 1994. Mostly c#, with history in VC++, Embedded C++, Delphi, and Modular 2. Working in the finanical sector.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberMarkLTX4:56 27 Mar '12  
QuestionConflicts with existing TypeConverter [modified] PinmemberMarkLTX5:03 26 Mar '12  
GeneralMy vote of 5 PinmemberScruffyDuck10:53 19 Oct '11  
GeneralMy vote of 5 PinmemberKPetrosyan1:09 26 Apr '11  
GeneralMy vote of 5 PinmemberEddy Vluggen9:43 21 Mar '11  
GeneralNice Work Pinmemberinfosarang18:36 16 Jun '10  
Generalmodification to allow auto ordering PinmemberMike Manfredi4:51 28 Apr '10  
GeneralIn multiple Categories, the sort does not work... Pinmemberze_tedesco2:25 6 Nov '07  
GeneralVery nice solution PinmemberDave197519954:29 12 Oct '07  
GeneralRe: Very nice solution PinmemberAloneSoul21:00 24 Oct '07  
QuestionOrder first by category and then the property order? Pinmembersaho5:55 25 Sep '07  
GeneralVB translation PinmemberTWallick11:18 19 Sep '07  
GeneralMultiple selection Pinmembernedoma4:20 29 Jul '07  
GeneralThanks , and one comment Pinmembercaddzooks23:01 28 Jun '07  
General3 years later and still AWESOME PinmemberCrankItOut12:17 14 Mar '07  
GeneralFantastic PinmemberBen Ratzlaff9:04 7 Feb '07  
GeneralExcellent! PinprotectorMarc Clifton6:55 9 Jul '06  
QuestionHow set order dynamically? Pinmemberokcode21:21 3 Jun '06  
Generalerror-entry point not defined & directive missing Pinmembersasire181:46 3 Feb '06  
GeneralRe: error-entry point not defined & directive missing Pinmemberwillydemis10:24 6 Oct '07  
GeneralEliminating items Pinmemberjstiff21:14 19 Aug '04  
GeneralCategory Ordering PinmemberRyan McFarren4:30 14 Jun '04  
GeneralRe: Category Ordering PinmemberRyan McFarren7:15 27 Apr '05  
GeneralThanks! PinmemberRick Pingry12:08 13 Jun '04  
GeneralRe: Thanks! Pinmemberalias471:37 10 Aug '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 6 Apr 2004
Article Copyright 2004 by Paul Tingey
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid