Search code examples
c#listpropertiesdesigner

How to properly expose a List<object> property in Visual Studio C#?


I have created a property to a custom windows form I made.

private List<object> values;

public List<object> Values
{
    get
    {
       return values;
    }
    set
    {
       values = value;
    }
}

It shows up in the property window on designer just fine. I go to the property value field and the button with '...' three dots shows. I click on the button and the window with which allows me to add items to list appears. I add them and click ok. No erro appears, but the items have not been saved.

My question is how to properly set this up so I can set the List<object> items in the property windows while in design?


Solution

  • In your Form1.Designer.cs, manually instantiate the List like this

    this.Values = new List<object>();
    

    After you've added items, the Form1.Designer.cs file will be recreated as per normal but the line above will be replaced by

    this.Values = ((System.Collections.Generic.List<object>)(resources.GetObject("$this.Values")));
    

    Alternatively, instantiate the list when you declare it.

    private List<object> values = new List<object>();
    
    public List<object> Values
    {
        get
        {
            return values;
        }
        set
        {
            values = value;
        }
     }