4

我正在尝试获取的关键,SelectedItemComboBox不知道如何获取我所做的代码,

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

2 回答 2

14

在这种情况下,字典只是键值对的集合,因此 上的每个项目ComboBox都是一个KeyValuePair<YourKeyType, YourValueType>. 投射SelectedItem到 aKeyValuePair<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;
于 2014-04-15T21:50:24.087 回答
3

尝试这个:

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

于 2018-08-15T04:38:12.830 回答