【问题标题】:C# Winforms - setting combobox selected valueC# Winforms - 设置组合框选定值
【发布时间】:2017-01-30 19:42:06
【问题描述】:

我想为组合框设置名称和值对。所以我创建了一个名为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()。
  • SelectedItem,获取或设置ComboBox中当前选中的项。

标签: c# winforms combobox selectedvalue


【解决方案1】:

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;

【讨论】:

  • 我知道,这个文本框是用来询问更多信息的,但非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多