I have a PropertyGrid in my winforms application that displays the some of the selected object's properties. I want that a certain property will be sometimes displayed and somtimes won't, by my choice, (lets assume the the browsability changes every time a specific button is pressed at runtime). Setting-up the browsability before runtime is pretty easy, using the BrowsableAttribute, from what I understand that attributes are set at design time hence I need another solution. In many places I found this piece of code:
public static void ChangeBrowsability(SomeObject obj, string propertyName, bool isBrowsable)
{//usage: supposed to change browsability at runtime
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(obj)[propertyName];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo browsableField = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
browsableField.SetValue(attrib, isBrowsable);
}
The first problem is the browsableField
is always null for some reason, and I would like to know why.
Also an alternative solution to this code may be welcomed.