Question

I have a PropertyGrid control to which I bind a container with an array of complex objects:

// Collection
public class ParametersCollection
{
    private ParameterObject [] _parameters = null;

    [Category("SubReportParams")]
    public ParameterObject [] Parameters 
    { 
        get { return _parameters; }
        set { _parameters = value; } 
    }

    public ParametersCollection()
    {
        // _parameters initialization here...
    }
}

// Complex object
public class ParameterObject
{
    private string _name = "";
    private string _value = "";

    [Category("Information"), DisplayName("Name")]
    public string Name 
    { 
       get { return _name; } 
       set { _name = value; } 
    }

    [Category("Information"), DisplayName("Value")]
    public string Value 
    { 
       get { return _value; } 
       set { _value = value; } 
    }
}

Everything works fine, except two cases:

  1. In example, if array _parameters has only 2 items, default array size is 4 and items with indexes 2 and 3 are nulls. PropertyGrid displays these items as empty fields. How to force PropertyGrid to ignore these fields and simply not displaying it?

  2. _parameters variable is an array type, so _parameters items are displayed with their indexes from 0 to n. Is there a posibillity to display them with their names from property ParamObject.Name instead of their indexes from an array?

Was it helpful?

Solution

For the fist question, the easiest way is to add a "fake" property computed from the "real" property. It's not perfect, but you can use various attribute to help:

  • DisplayName to give the fake property the name of the real property
  • Browsable(false) instructs the property grid to skip the real property
  • EditorBrowsable(never) instructs Visual Studio's intellisense to not show this property in external code.

        [Browsable(false)]
        public ParameterObject[] Parameters
        {
            get { return _parameters; }
            set { _parameters = value; }
        }
    
        [Category("SubReportParams"), DisplayName("Parameters")]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public ParameterObject[] NonEmptyParameters
        {
            get
            {
                return _parameters.Where(p => p != null).ToArray();
            }
        }
    

For the second question, one simple way is to add a ToString() implementation like this:

public class ParameterObject
{
    public override string ToString()
    {
        return Name;
    }
}

Otherwise, you can to add a custom TypeConverter to the class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top