PropertyGrids in C#

Yesterday, An example property gridI decided to tackle .Net’s PropertyGrid component: for Helios, I was working on code to allow users to view Datasource-specific data at run-time. For this, I already had several support objects programmed and ready to go, and what better to test them right in that PropertyGrid component?

This worked out easier than I thought: Basically, the only thing you need to do as a programmer is to actually create those objects and assign it to ‘SelectedObject’ property of the component. This works in most cases, however, I had a TServerPropertyObject contained inside a TDataSourceObject (half-pseudocode follows):

public class TServerPropertyObject
{
     public string GroupByBehaviour {get; set;}
     public string IdentifierCase{get; set;}
     // etc...
}

public class TDataSourceObject
{
     private TServerPropertyObject fserverproperties = 
             new TServerPropertyObject();

     public string ServerName {get; set; }

     public string DSN { get; set; }

     public TServerPropertyObject Properties { 
          get { return fserverproperties; }
     }
}

Obviously, the idea is to have the properties object of TDataSourceObject to show as a ‘collapsible’ item in the PropertyGrid component. To achieve this, you need to add (those devilish) so called ‘property attributes’ (I believe these are the only things that makes .Net look evil). In our case of the collapsible item, we’re going to use the ‘TypeConverter’ class and pass it the ExpandableObjectConvertor type.

public class TDataSourceObject
{
     private TServerPropertyObject fserverproperties = 
             new TServerPropertyObject();

     public string ServerName {get; set; }

     public string DSN { get; set; }

     // Make this property expandable and let .Net
     // figure out what to do with the object.
     [ TypeConverter(
           typeof(ExpandableObjectConverter)),
        Category("Connection"),
        Description("Server properties")]
     public TServerPropertyObject Properties { 
          get { return fserverproperties; }
     }
}

This will let .Net handle (and figure out) what to do with the object itself: In my case the contained object only exposed simple types (like strings and integers). Naturally, you’ll have to do a lot more work (read coding) when your objects (and components) need specialized ‘property-editors': for that, I have to refer you to the .Net documentation.

Update: See also here for more context and a larger screenshot (outdated though but still relevant).