How do you control what is visible in a property grid at runtime?

c#, propertygrid, winforms

Solution

Here is an example:

PropertyDescriptor descriptor=
  TypeDescriptor.GetProperties(this.GetType())["DataType"];
BrowsableAttribute attrib= 
  (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)]; 
FieldInfo isBrow = 
  attrib.GetType().GetField("browsable",BindingFlags.NonPublic | BindingFlags.Instance);
isBrow.SetValue(attrib,false);

Just replace `DataType` with your property name. Note, all properties must have the attribute being changed (in this case, Browsable). If one of the properties is missing the attribute, all of the class properties get the new attribute setting.

Code taken from here: Exploring the Behaviour of Property Grid.

Problem

I have a property grid displaying a list, for example of a class `Person` ``` [TypeConverter(typeof(ExpandableObjectConverter))] public class Person { public bool ShowHidden { get; set; } public string Name { get; set; } //[Browsable(false)] public string Hidden { get; set; } public override string ToString() { return string.Format("Person({0})", Name); } } ``` The question is how do I control the `Browsable()` attribute at runtime such that when `ShowHidden = false` the `Hidden` line (highlighted yellow below) is omitted. Thanks.

Original source