我有一个组合框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;
}
但是当我尝试获取密钥时,它会显示价值 使用此代码
MessageBox.Show(cmbCourses.SelectedItem.ToString());
答案 0 :(得分:1)
您可以使用GetValue()方法获取值而不是显示文本:
MessageBox.Show(cmbCourses.GetValue().ToString());
答案 1 :(得分:1)
似乎您在向组合框添加项目时遇到问题,您只是按此行cmbCourses.Items.Add(a.Value);
添加了值,您可以试试这个:
cmbCourses.Items.Add(item);
然后您可以使用此行获取值:
MessageBox.Show(cmbCourses.SelectedValue.ToString());
别忘了为你的组合框设置这些:
cmbCourses.DisplayMember = "YOUR DISPLAY FIELD NAME";
cmbCourses.ValueMember = "YOUR VALUE FIELD NAME";
答案 2 :(得分:1)
您只是将值添加到ComboBox
。将KeyValuePair
添加到ComboBox
并设置DisplayMemberPath
和SelectedValuePath
属性:
var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
cmbCourses.Items.Add(a);
}
cmbCourses.DisplayMemberPath = "Value";
cmbCourses.SelectedValuePath = "Key";
然后您可以像这样获取所选项目的键:
var item = cmbCourses.SelectedItem as KeyValuePair<int, String>;
if (item != null)
MessageBox.Show(item.Key);