Search code examples
c#.netwinformsgeneric-collections

Use List of custom Business Objects as ComboBox datasource


I have class like this:

class MyClass     {
    public string FirstProperty { get; set; }

    public int SecondProperty { get; set; }

public MyClass(int i, string s)
{
    FirstProperty = s;
    SecondProperty = i;
}   

        }

and a Winform with code like this:

List<MyClass> myList = new List<MyClass>();
myList.Add(new MyClass(1, "ABC"));
myList.Add(new MyClass(2, "ZXC"));

comboBox1.DataSource = myList;
comboBox1.ValueMember = "FirstProperty";
comboBox1.DisplayMember = "SecondProperty";

When I execute this code it fauls with "Cannot bind to new display member". This has worked for me in the past. What am I doing wrong?


Solution

  • public class MyClass
    {
        public string FirstProperty { get; set; }
        public int SecondProperty { get; set; }
    }
    

    Then:

    var myList = new List<MyClass>
    {
        new MyClass {SecondProperty = 1, FirstProperty = "ABC"},
        new MyClass {SecondProperty = 2, FirstProperty = "ZXC"}
    };
    
    comboBox1.DataSource = myList;
    comboBox1.ValueMember = "FirstProperty";
    comboBox1.DisplayMember = "SecondProperty";
    

    I hope it helps.