我希望为下拉框设置名称和值的组合。所以我创建了一个叫做 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时,非洲大陆应该被选中,但实际上并没有。我无法解决这个问题。