【问题标题】:How to get key from SelectedItem of ComboBox?如何从 ComboBox 的 SelectedItem 中获取密钥?
【发布时间】:2018-08-15 12:38:12
【问题描述】:

我正在尝试获取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";

【问题讨论】:

    标签: c# combobox keyvaluepair


    【解决方案1】:

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

    【讨论】:

    • 您更简单的方法给出了 InvalidCastException。
    • @iheanyi 你设置了ValueMember,如原帖所示?来自the documentation of SelectedValue:“如果ValueMember中没有指定属性,SelectedValue返回对象的ToString方法的结果。”
    • 我收回我之前的评论。原来我没有设置ValueMember。我实际上有两个组合框,复制粘贴的代码并忘记更改我真正关心的ValueMember 的组合框名称。这些名称非常相似,以至于我花了一段时间才意识到我的错误,即使在对代码进行了几次编辑之后也是如此。
    • 我试过了,我的第一条评论中提到了错误。确信我没有做错任何事,我对你的回答投了反对票。我只是在需要对您的答案进行编辑的情况下撤消否决票为时已晚后才意识到自己的错误。
    • @iheanyi 您只需再次点击向下投票箭头即可撤消拒绝投票。
    【解决方案2】:

    试试这个:

    string key = ((KeyValuePair )comboBox1.SelectedItem).Key;

    【讨论】:

    • 我无法从上面的答案中克服 InvalidCastException(我确定是我的错),这个效果很好。谢谢
    猜你喜欢
    • 1970-01-01
    • 2015-03-13
    • 2019-07-09
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多