C# Winforms - 设置下拉框选定的值

4

我希望为下拉框设置名称和值的组合。所以我创建了一个叫做 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()。 - Ross Bush
1
SelectedItem,获取或设置ComboBox中当前选定的项。 - bashkan
1个回答

7
SelectedValue属性文档所述:

属性值
包含由ValueMember属性指定的数据源成员的值的对象。

备注
如果在ValueMember中未指定属性,则SelectedValue返回对象的ToString方法的结果。

要获取所需的行为,您需要将NameValue公开为您的Item类的公共属性,并利用控件的DataSourceValueMemberDisplayMember属性。
// Content item for the combo box
private class Item
{
    public string Name { get; private set; }
    public int Value { get; private set; }
    private Item(string _name, int _value)
    {
        Name = _name; Value = _value;
    }
}

并且这是一个示例用法:

// Build a list with items
var items = new List<Item>();
// For example get from database continentals.
var gets = _connection.Continentals;
items.Add(new Item("--- Select a continental. ---", 0));
foreach (var get in gets)
{
    items.Add(new Item(get.name.Length > 40 ? get.name.Substring(0, 37) + "..." : get.name, Convert.ToInt32(get.id)));
}
// Bind combobox list to the items
comboBox1.DisplayMember = "Name"; // will display Name property
comboBox1.ValueMember = "Value"; // will select Value property
comboBox1.DataSource = item; // assign list (will populate comboBox1.Items)

// Will select Africa
comboBox1.SelectedValue = 3;

2
我知道,这个文本框是用来询问更多信息的,但非常感谢您的帮助。 - user1372430

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接