Saturday 5 July 2008

Dynamic PropertyGrid

People seem to be stumbling across my blog after searching for how to create a dynamic property grid with attributes in c#.

Presumably, people want to be able to hide some fields, and make others read only, which can be done easily at design time by adding "Browsable" and "ReadOnly" attributes. But try to find any information on the Internet about changing those attributes at runtime and you'll find yourself crashing straight into a brick wall.

From what I gather, attributes are compiled into the executable, so being allowed to change them dynamically at runtime would mean making changes to the executable - which is probably a Bad Thing(TM). Which means it can't be done.

What you end up having to do, is creating a dynamic class, on-the-fly, containing the fields that you want to appear in the property grid, then creating property descriptors per property. Then when the property grid is dismissed, copying the data out of the temporary class back into your original class.

There's a sample over at CodeProject.

Good luck!

No comments: