Readonly PropertyGrid

Eric Anastas picture Eric Anastas · Feb 23, 2010 · Viewed 8k times · Source

I'm using a PropertyGrid in an application I am writing to allow users to view and sometimes edit instances of my objects. Sometimes the user may have a file open in read/write mode where they can make changes to the file through the property grid. In other cases they may have a file open in read only mode, and should not be able to make any changes to the objects through the PropetyGrid. My classes also have dynamic properties which are returned by implementing ICustomTypeDescriptor. Which is why I really want to take advantage of the built in flexibility of a PropertyGrid control.

There doesn't seem to be an easy way to set a Property-grid to a read only mode. If I disable a PropertyGrid this also prevents the user from scrolling the list. So I'm thinking the best way to do this is to add ReadOnlyAttributes to the properties at run-time. Is there some other way?

Answer

Larry picture Larry · Dec 5, 2012

I have found a very quick solution for thoses who do not care about the propertygrid being grayed out.

TypeDescriptor.AddAttributes(myObject, new Attribute[]{new ReadOnlyAttribute(true)});
propertyGrid1.SelectedObject = myObject;