C# Winforms - 设置组合框选定值

2 c# combobox selectedvalue winforms

我想为组合框设置名称和值对。所以我创建了一个这样命名的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和这样的数据集:

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;
Run Code Online (Sandbox Code Playgroud)

这是输出:

// 1 - Europe
// 2 - Asia
// 3 - Africa
// 4 - North America
// 5 - South America
// 6 - Australia
// 7 - Antartica
Run Code Online (Sandbox Code Playgroud)

在我的示例中,必须选择非洲大陆,但事实并非如此。不仅仅是在我的编辑表单中,例如这段代码从person表中获取数据:

var a = _connection.persons.SingleOrDefault(x => x.id == Id);

当我编码时comboBox2.SelectedValue = a.continental,必须选择非洲大陆,但事实并非如此。我没有解决问题。

Iva*_*oev 5

SelectedValue属性文档中所述:

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

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

要获得所需的行为,您需要将NameValue作为Item类的公共属性公开并利用控件的DataSource,ValueMemberDisplayMember属性:

// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和示例用法:

// 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;
Run Code Online (Sandbox Code Playgroud)

  • 我知道,这个文本框是为了询问更多信息,但非常感谢您的帮助。 (2认同)