gpt4 book ai didi

c# - 如何从 ComboBox 的 SelectedItem 中获取 key?

转载 作者:太空狗 更新时间:2023-10-30 00:04:57 25 4
gpt4 key购买 nike

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

我是这样绑定(bind)组合框的,

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

最佳答案

在这种情况下,字典只是键值对的集合,所以 ComboBox 上的每一项是 KeyValuePair<YourKeyType, YourValueType> .投SelectedItemKeyValuePair<YourKeyType, YourValueType>然后你就可以读取 key 了。

// 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属性(property)。

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

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

关于c# - 如何从 ComboBox 的 SelectedItem 中获取 key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23095060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com