【发布时间】:2017-01-30 19:42:06
【问题描述】:
我想为组合框设置名称和值对。所以我创建了一个名为Item 的类,如下所示:
// Content item for the combo box
private class Item
{
private readonly string Name;
private readonly int Value;
private Item(string _name, int _value)
{
Name = _name; Value = _value;
}
private override string ToString()
{
// Generates the text shown in the combo box
return Name;
}
}
还有这样的数据集:
comboBox1.DataSource = null;
comboBox1.Items.Clear();
// For example get from database continentals.
var gets = _connection.Continentals;
comboBox1.Items.Add(new Item("--- Select a continental. ---", 0));
foreach (var get in gets)
{
comboBox1.Items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id)));
}
// It points Africa.
comboBox1.SelectedValue = 3;
这是输出:
// 1 - Europe
// 2 - Asia
// 3 - Africa
// 4 - North America
// 5 - South America
// 6 - Australia
// 7 - Antartica
在我的示例中,必须选择非洲大陆,但不是。
不仅如此,在我的编辑表单中,例如此代码从person 表中获取数据:
var a = _connection.persons.SingleOrDefault(x => x.id == Id);
当我编码comboBox2.SelectedValue = a.continental时,必须选择非洲大陆,但不是。我没有解决问题。
【问题讨论】:
-
我认为你需要 SelectedIndex=3 或 SelectedIndex=IndexOf()。
-
SelectedItem,获取或设置ComboBox中当前选中的项。
标签: c# winforms combobox selectedvalue