9

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.

Screenshot

Thanks.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133

1 Answers1

15

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.

iheanyi
  • 3,107
  • 2
  • 23
  • 22
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • Thanks for the hint. I have not made it to work yet. I can't figure out what is the best placement for this snippet. I have it in a property setter, but I see not effect on my grid. – John Alexiou Dec 03 '12 at 19:59
  • What I expected was to remove only the row for the instance that has `ShowHidden = false`, but it removes the row from all instances. I will accept the answer as it did kinda what I need. – John Alexiou Dec 05 '12 at 12:26
  • 2
    The code changes the BrowsableAttribute, but I don' t see the change in grid...how can I see changes runtime? – FrancescoDS Feb 18 '15 at 11:17
  • @FrancescoDS: You should be able to see changes at runtime. Please post a new question if you have issues with this approach. Based on the number of upvotes, I'd assume it worked for others. – Victor Zakharov Feb 18 '15 at 14:19
  • I had to put another line at the bottom of the code to make this work, something like: descriptor.SetValue(this, attrib); I think the componentchange/changing sequence takes effect after the setValueis called on the base object. – Rajnish Sinha Apr 21 '15 at 15:24
  • 1
    @ja2 The reason it was hiding all your properties is because this only works when all the properties have a Browsable attribute. The source link mentions this issue. – iheanyi Sep 21 '15 at 21:47