user3244721 user3244721 - 2 months ago 14
C# Question

Cannot bind to the new display member in combobox C#

I have a class which give me this error

public class Item
public string Name;
public int Id

public Item(string name, int id)
Name = name;
Id = id;

Here is my function

var lstItems = new List<Item>();
lstItems.Add(new Item(sAd_Ref, Convert.ToInt32(sAd_ID)));
comboBox1.DataSource = lstItems;
comboBox1.ValueMember = "Id";

On second last line i am getting exception of "Cannot bind to the new display member".


You should make Name and Id properties. You can't bind ComboBox to fields.

public string Name { get; set; }
public int Id { get; set; }

It's also stated in docs:

ValueMember Property: Gets or sets the property to use as the actual value for the items in the System.Windows.Forms.ListControl.