Wednesday, May 11, 2011

Property Grid

So this is probably not something you would use everyday but a cool feature in .NET is the Property Grid control.  This control accepts an object and displays the public properties of that object int he same fashion as the property window inside of .NET.  It also allows editing of those properties that have a setter available.

I'm using this for a "What If" calculator that is geared towards developer testing of our loan decisioning code.  We are also hoping to expand this to be used by our customer's auditor(s).

Usage

Drop the control on your form and then simply set the "SelectedObject" property to the object you want to display.

Ex. 

object someObject = new object();
propertyGrid1.SelectedObject = someObject;

Advanced Steps

You'll notice that by default the object is a jumbled mess when it is displayed.  There is a very quick and easy way (no code required) to really clean this up.

First, go to your object and make sure you have the using statement for "System.ComponentModel".  This will enable you do add Attributes which the Property Grid will make use of at run-time.

Browsable:  This will tell the property grid not to display an object or property.  Above that property you simply put [Browsable(false)].

Category:  Like the IDE, this grid offers the options of sorting alphabetically or to group properties.  Useage is [Category("Name Here")] about the property that you want to group into  a given category.  Note: You can only assign one category per property.  I found that to be a bit of a bummer but you could always create another property that accesses the same variable and assign it to another category I suppose.

Those are just two of the attributes available.  Some other useful ones are for read-only, default value, and a user friendly description of the field.


No comments:

Post a Comment