Can't get Value from ComboBox

前端 未结 6 2096
时光取名叫无心
时光取名叫无心 2021-01-15 16:04

I have a simple comboBox with some Value/Text items in it. I have using ComboBox.DisplayMember and ComboBox.ValueMember to correctly set the value/text. When I try to get th

6条回答
  •  礼貌的吻别
    2021-01-15 16:39

    To avoid having to create a new class for all your comboboxes I would suggest you just use a KeyValuePair like in the following example:

    cbPlayer1.ValueMember = "Value";
    cbPlayer1.DisplayMember = "Key";
    
    cbPlayer1.DataSource = new List>()
    {new KeyValuePair("3","This should have the value of 3")};
    

    You still need to cast the selected value

    string selectedValue = (string)cbPlayer1.SelectedValue;
    
    MessageBox.Show(selectedValue);
    

提交回复
热议问题