[英]How to get value of ComboBox rather than text
I have a combobox cmbCourses
and I am populating my this code 我有一个组合框
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;
}
But when I try to get key it shows value instead using this code 但是当我尝试获取密钥时,它会使用此代码显示值
MessageBox.Show(cmbCourses.SelectedItem.ToString());
您可以使用GetValue()方法获取值而不是显示文本:
MessageBox.Show(cmbCourses.GetValue().ToString());
Seems you have problem in adding items to your combobox, you are adding only the value by this line cmbCourses.Items.Add(a.Value);
似乎您在向组合框中添加项目时遇到问题,您只是通过此行添加值
cmbCourses.Items.Add(a.Value);
, Can you try this : 你能试试这个:
cmbCourses.Items.Add(item);
Then you can use this line to get the value : 然后你可以使用这一行来获取值:
MessageBox.Show(cmbCourses.SelectedValue.ToString());
Don't forget to set these for your combobox : 别忘了为你的组合框设置这些:
cmbCourses.DisplayMember = "YOUR DISPLAY FIELD NAME";
cmbCourses.ValueMember = "YOUR VALUE FIELD NAME";
You are only adding the value to the ComboBox
. 您只是将值添加到
ComboBox
。 Add the KeyValuePair
to the ComboBox
and set the DisplayMemberPath
and SelectedValuePath
properties: 将
KeyValuePair
添加到ComboBox
并设置DisplayMemberPath
和SelectedValuePath
属性:
var _courses = new DatabaseHandler().GetAllCourses();
foreach (var a in _courses)
{
cmbCourses.Items.Add(a);
}
cmbCourses.DisplayMemberPath = "Value";
cmbCourses.SelectedValuePath = "Key";
You can then get the key of the selected item like this: 然后,您可以像这样获取所选项目的键:
var item = cmbCourses.SelectedItem as KeyValuePair<int, String>;
if (item != null)
MessageBox.Show(item.Key);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.