Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComboBox.ValueMember and DisplayMember

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.DataSource = dataTable;
ComboBox1.ValueMember = "id"; // --> once hes here, he just jumps out the method
ComboBox1.DisplayMember = "name";

No compilation error, warning, nothing.. just jumps out!

This is the query to fill the DataTable

"Select * from \"Table\""

I checked with the debugger and the datatable was filled. The columns names are "id" and "name". ComboBox is blank. I'm filling it for the first time!

like image 971
dbncourt Avatar asked Mar 01 '12 18:03

dbncourt


2 Answers

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<string, string>(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.

like image 156
flodis Avatar answered Oct 23 '22 04:10

flodis


You should not set datasource of your listbox and/or combobox in this order

ComboBox1.DataSource = dataTable;

ComboBox1.ValueMember = "id"; 

ComboBox1.DisplayMember = "name";

Instead, this is correct order:

ComboBox1.ValueMember = "id"; 

ComboBox1.DisplayMember = "name";

ComboBox1.DataSource = dataTable;

NOTE: setting datasource should be last line.

If you set datasource first, SelectedIndexChanged event will fire and you may get the cast error or other exception.

like image 26
Visitor Avatar answered Oct 23 '22 04:10

Visitor