ComboBox.ValueMember and DisplayMember

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.

Leave a Comment