当我有ID时,C#ComboBox设置索引

时间:2013-10-15 20:30:15

标签: c# combobox

我的课程类似于:

class ComboboxValue
{
  public int Id { get; private set; }
  public string Name { get; private set; }

  public ComboboxValue(int id, string name)
  {
    Id = id;
    Name = name;
  }

  public override string ToString()
  {
    return Name;
  }
}

要从Combobox中获取选定的值,我使用:

Combobox cb = new Combobox();
cb.Items.Add(new ComboboxValue(10, "Example value"));
ComboboxValue tmpComboboxValue = (ComboboxValue)cb.SelectedItem;

但是当我知道以前存储的ID时,如何设置ComboBox的索引? ...对于此示例,ID:10(来自sql查询)

1 个答案:

答案 0 :(得分:0)

这是第一个涉及跟踪您在ComboBox中填充的项目的解决方案:

// Populate the ComboBox
var values = new ComboBoxValue[]
{
    new ComboBoxValue() { ID = 1, Name = "Test" },
    new ComboBoxValue() { ID = 2, Name = "Test 2" },
};

comboBox1.Items.AddRange(values);

...

// Set selected item based on an ID
int id = 1;
comboBox1.SelectedItem = values.Single(x => x.ID == id);

如果你将实例传递给类而不仅仅是id,你可以写cb.SelectedItem = item

您还可以利用ComboBox的ValueMemberSelectedValue属性来做得更好一些。您必须先设置ComboBox的DataSource属性才能执行此操作。您应该能够将DataSource设置为一个简单的列表。

var values = new ComboBoxValue[]
{
    new ComboBoxValue() { ID = 1, Name = "Test" },
    new ComboBoxValue() { ID = 2, Name = "Test 2" },
};

comboBox1.DataSource = values;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";

comboBox1.SelectedValue = 1;