Cannot bind to the new display member in ComboBox

后端 未结 9 684
迷失自我
迷失自我 2021-01-01 21:14

I have a class which give me this error

public class Item 
{
    public string Name;
    public int Id

    public Item(string name, int id) 
    {
        N         


        
相关标签:
9条回答
  • 2021-01-01 21:44

    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.

    0 讨论(0)
  • 2021-01-01 21:46

    My issue was that my dataSource was of Type List < string > so I just test for that

    public static void AddDataSource<T>(this ComboBox comboBox, T dataSource, string item)
    {
        comboBox.DataSource = dataSource;
    
        if (!typeof(T).Equals(typeof(List<string>))) // <-- Here
        {
            comboBox.DisplayMember = "Name";
            comboBox.ValueMember = "Value";
        }
    
        comboBox.SelectedIndex = -1;
        comboBox.Text = $"Select a {item}";
    }
    
    0 讨论(0)
  • 2021-01-01 21:47

    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;
    
    0 讨论(0)
提交回复
热议问题