繁体   English   中英

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

[英]C# Winforms - setting combobox selected value

我想为组合框设置名称和值对。 因此,我创建了一个名为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 ,必须选择非洲大陆,但不是。 我没有解决问题。

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM