如何从组合框的SelectedItem中获取键

本文关键字:SelectedItem 获取 组合 | 更新日期: 2023-09-27 17:58:41

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

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";

如何从组合框的SelectedItem中获取键

在这种情况下,字典只是键值对的集合,因此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;

试试这个:

string key=((KeyValuePair<string,string>)comboBox1.SelectedItem).key;