The easiest way to hide a property in PropertGrid and in a Custom Control for me is this:
public class Question
{
...
[Browsable(false)]
public int Element
{
get; set;
}
}
To do it dynamically you can use this code, where Question is your class and your property is Element, so you can show or hide it without remove element from collection:
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
//Condition to Show or Hide set here:
isBrow.SetValue(attrib, true);
propertyGrid1.Refresh(); //Remember to refresh PropertyGrid to reflect your changes
So to refine the answer:
public class Question
{
...
private int element;
[Browsable(false)]
public int Element
{
get { return element; }
set {
element = value;
PropertyDescriptorCollection propCollection = TypeDescriptor.GetProperties(Question.GetType());
PropertyDescriptor descriptor = propCollection["Element"];
BrowsableAttribute attrib = (BrowsableAttribute)descriptor.Attributes[typeof(BrowsableAttribute)];
FieldInfo isBrow = attrib.GetType().GetField("browsable", BindingFlags.NonPublic | BindingFlags.Instance);
if(element==0)
{
isBrow.SetValue(attrib, false);
}
else
{
isBrow.SetValue(attrib, true);
}
}
}
}