C# Winforms - 设置组合框选择的值

C# Winforms - setting combobox selected value

我想为组合框设置名称和值对。所以我创建了一个名为 Item 的 class,如下所示:

// 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 table:

获取数据

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

我在编码comboBox2.SelectedValue = a.continental的时候,必须选择非洲大陆,但是没有。我没有解决问题。

SelectedValue 属性 文档中所述:

Property Value
An object containing the value of the member of the data source specified by the ValueMember property.

Remarks
If a property is not specified in ValueMember, SelectedValue returns the results of the ToString method of the object.

要获得所需的行为,您需要将 NameValue 公开为 Item class 的 public 属性并利用 [=控件的 16=、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;
    }
}

和示例用法:

// 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;