2

This is a concept I cannot understand. I have a class

    Class Employee
    {
    public int id;
    public string name;
    }

    List<Employee> lst = new List<Employee>();
                Employee o = new Employee();
                o.id = 1;
                o.name = "Darshan";
                lst.Add(o);
                Employee o1 = new Employee();
                o1.id = 2;
                o1.name = "Gopal";
                lst.Add(o1);



 comboBox1.DisplayMember = "name";
        comboBox1.ValueMember = "name";
        comboBox1.DataSource = lst;

The above doesn't work. But when I change the public fields with get and set, then it works.

Is there any way I can bind without get and set properties?

Public fields are also accessible outside class. You can read and write the value of that field anywhere. Then why can't we use them in Binding? Why to use properties?

halfer
  • 19,824
  • 17
  • 99
  • 186
Gopal
  • 57
  • 6

1 Answers1

1

If you look at the documentation:

DisplayMember Property: Gets or sets the property to display for the System.Windows.Forms.ListControl.

When you add get and set your fields become properties.And DisplayMember and ValueMember looks for a property named "name" in your class.Not a field.Without get and set you just have fields which you cannot use for bindings like that.See this question for more details about properties and fields: What is the difference between a Field and a Property in C#?

Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184