ComboBox.ValueMember and DisplayMember

后端 未结 8 1577
野的像风
野的像风 2020-12-06 12:45

How do i set this values? I have a DataTable with all the data i want to set in the combobox, but i cant find how to set it.

I tried

ComboBox1.DataSo         


        
8条回答
  •  孤街浪徒
    2020-12-06 13:27

    Using keyvalue pairs to populate a combobox

    A neat way to populate combo boxes is to set the datasource to a list of keyvalue pairs. It may also inspire using data stored in a list of some kind:

    //Some values to show in combobox
    string[] ports= new string[3] {"COM1", "COM2", "COM3"};
    
    //Set datasource to string array converted to list of keyvaluepairs
    combobox.Datasource = ports.Select(p => new KeyValuePair(p, p)).ToList();
    
    //Configure the combo control
    combobox.DisplayMember = "Key";
    combobox.ValueMember = "Value";
    combobox.SelectedValue = ports[0];
    

    The datasource can be populated using this syntax as well:

    ports.Select(p => new { Key = p, Value = p }).ToList();
    

    The technicue may be expanded with more property names for multiple column lists.

提交回复
热议问题