如何从ComboBox的SelectedItem获取密钥?

时间:2014-04-15 21:41:16

标签: c# combobox keyvaluepair

我正在尝试获取SelectedItem ComboBox的密钥,但不知道如何获取我所做的代码,

void CboBoxSortingDatagridview(ComboBox sender)
{
    foreach (var v in DictionaryCellValueNeeded)
    {
        if (!DictionaryGeneralUsers.ContainsKey(v.Key) && v.Value.RoleId == Convert.ToInt32(((ComboBox)sender).SelectedItem)) // here getting value {1,Admin} i want key value which is 1 but how?
        {
            DictionaryGeneralUsers.Add(v.Key, (GeneralUser)v.Value);
        }
    }
    dataGridViewMain.DataSource = DictionaryGeneralUsers.Values;
}  

我以这种方式绑定了组合框,

cboRolesList.DataSource = new BindingSource(dictionaryRole, null);  
cboRolesList.DisplayMember = "Value";  
cboRolesList.ValueMember = "Key";

2 个答案:

答案 0 :(得分:13)

在这种情况下,词典只是键值对的集合,因此ComboBox上的每个项目都是KeyValuePair<YourKeyType, YourValueType>。将SelectedItem投射到KeyValuePair<YourKeyType, YourValueType>,然后您就可以阅读密钥。

// get ComboBox from sender
ComboBox comboBox = (ComboBox) sender;

// get selected KVP
KeyValuePair<YourKeyType, YourValueType> selectedEntry
    = (KeyValuePair<YourKeyType, YourValueType>) comboBox.SelectedItem;

// get selected Key
YourKeyType selectedKey = selectedEntry.Key;

或者,更简单的方法是使用SelectedValue属性。

// get ComboBox from sender
ComboBox comboBox = (ComboBox) sender;

// get selected Key
YourKeyType selectedKey = (YourKeyType) comboBox.SelectedValue;

答案 1 :(得分:1)

尝试一下:

字符串键=(((KeyValuePair <字符串,字符串>)comboBox1.SelectedItem).Key;