Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot bind to the new display member in ComboBox

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>();
 while(...)
 {
     lstItems.Add(new Item(sAd_Ref, Convert.ToInt32(sAd_ID))); 
 }

 comboBox1.DataSource = lstItems;
 comboBox1.ValueMember = "Id";
 comboBox1.DisplayMember = "Name";

On second to the last line I am getting exception of

Cannot bind to the new display member.

like image 853
user3244721 Avatar asked Sep 10 '14 09:09

user3244721


2 Answers

I know the post is old but the accepted answer is not correct. The Op needed to change the order of how he was assigning displayMember, valueMember and Datasource and then note the added line of code.

comboBox1.DisplayMember="Name";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = lstItems;
comboBox1.BindingContext = this.BindingContext;
like image 40
Ken Avatar answered Nov 09 '22 13:11

Ken


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.

like image 65
Selman Genç Avatar answered Nov 09 '22 13:11

Selman Genç