gpt4 book ai didi

c# - 如何获取 ComboBox 的值而不是文本

转载 作者:行者123 更新时间:2023-11-30 15:56:14 29 4
gpt4 key购买 nike

我有一个组合框cmbCourses,我正在填充我的代码

var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
ComboBoxItem item = new ComboBoxItem();
item.Text = a.Value;
item.Value = a.Key;

cmbCourses.Items.Add(a.Value);
}

public Dictionary<int, String> GetAllCourses()
{
Dictionary<int, String> courses = new Dictionary<int, String>();

var connection = DatabaseConnector.Instance();

if(connection.IsConnect())
{
connection.Connection.Open();
string query = "SELECT * FROM courses";
cmd = new MySqlCommand(query, connection.Connection);
cmd.Prepare();
var result = cmd.ExecuteReader();

while(result.Read())
{
courses.Add(result.GetInt16(0), result.GetString(1));
}
}
connection.Connection.Close();

return courses;
}

但是当我尝试获取 key 时,它显示的是值使用此代码

MessageBox.Show(cmbCourses.SelectedItem.ToString());

最佳答案

您只是将值添加到 ComboBox。将 KeyValuePair 添加到 ComboBox 并设置 DisplayMemberPathSelectedValuePath 属性:

var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
cmbCourses.Items.Add(a);
}
cmbCourses.DisplayMemberPath = "Value";
cmbCourses.SelectedValuePath = "Key";

然后您可以像这样获取所选项目的 key :

var item = cmbCourses.SelectedItem as KeyValuePair<int, String>;
if (item != null)
MessageBox.Show(item.Key);

关于c# - 如何获取 ComboBox 的值而不是文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47223458/

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