This project has moved. For the latest updates, please go here.

PropertyGrid: Dynamically add Properties or Hide Properties on Runtime.

Apr 13, 2016 at 5:39 AM
Good morning,

I'm searching for a way to dynamically hide properties that are 'String.IsNullOrEmpty'.
I tried using reflection:
  private void SetBrowsableProperty(string strPropertyName, bool bIsBrowsable)
        {

            PropertyDescriptor propertyDesc = TypeDescriptor.GetProperties(GetType())[strPropertyName];

            BrowsableAttribute attribute = (BrowsableAttribute)propertyDesc.Attributes[typeof(BrowsableAttribute)];
            FieldInfo fiedInfo = attribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);

            fiedInfo.SetValue(attribute, bIsBrowsable);
        }
..to set the Browsable Attribute, but that causes the Properties in the PropertyGrid to dissapear completely, independent if they have a value or not.

Any help is highly appreciated.
Apr 13, 2016 at 8:51 AM
Got it working.
The trick was to set the Browsable Attribute to true on all properties, then call the SetBrowsableProperty in the setter of the property.
        [Category("Projekt")]
        [PropertyOrder(1)]
        [DisplayName("Projectnumber")]
        [Browsable(true)]
        public string ProjectNumber
        {
            get
            {
                return _projectNumber;
            }
            set
            {
                _projectNumber = value;
                SetBrowsableProperty("ProjectNumber", !String.IsNullOrEmpty(_projectNumber));
            }
        }

        private void SetBrowsableProperty(string strPropertyName, bool bIsBrowsable)
        {

            PropertyDescriptor propertyDesc = TypeDescriptor.GetProperties(GetType())[strPropertyName];

            BrowsableAttribute attribute = (BrowsableAttribute)propertyDesc.Attributes[typeof(BrowsableAttribute)];
            FieldInfo fiedInfo = attribute.GetType().GetField("Browsable", BindingFlags.IgnoreCase | BindingFlags.NonPublic | BindingFlags.Instance);

            fiedInfo.SetValue(attribute, bIsBrowsable);
        }

Marked as answer by j_to_the_4n on 4/13/2016 at 1:51 AM