Reputation: 334
I have a WinForms application. I have added a datasource to my ComboBox as below:
DataSource:
public static Dictionary<byte, string> Ltype = new Dictionary<byte, string>()
{
{1 , "Type1"},
{2 , "Type2"},
{3 , "Type3"},
{4 , "Type4"}
};
Combobox Initialization:
cmbType.DataSource = new BindingSource(Ltype, null);
cmbType.DisplayMember = "Value";
cmbType.ValueMember = "Key";
cmbType.KeyUp += (s, e) =>
{
cmbType.DroppedDown = true;
};
I set the value of combobox like below but its does nothing it sets the value to "Type1"(as it would have even if I don't use SelectedValue). I cannot programatically set the value. Also when I debug, the value of cmbType.SelectedValue
is still null
after the SelectedValue is executed.
cmbType.SelectedValue = 2;
I have also tried to do something like this but still the same:
cmbType.SelectedValue = "2";
Please help me if I am missing something here.
Upvotes: 1
Views: 459
Reputation: 334
I found this thread here which is working for me:
Why ComboBox.SelectedValue does not work...
I updated my code as below and it is working now:
cmbType.DataSource = new BindingSource(gltype, null);
//cmbType.DisplayMember = "Key";
//cmbType.ValueMember = "Value";
cmbType.DisplayMember = "Value";
cmbType.ValueMember = "Key";
cmbType.KeyUp += (s, e) =>
{
cmbType.DroppedDown = true;
};
*//added new line*
**cmbType.BindingContext = new BindingContext();**
Upvotes: 0
Reputation: 197
Do you want to set the default value as type1?
cmbType.SelectedIndex = 0;
Upvotes: 1