简体   繁体   中英

C# ComboBox.SelectedValue not working as expected

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.

Do you want to set the default value as type1?

   cmbType.SelectedIndex = 0;

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();**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM