【发布时间】:2010-09-03 06:06:12
【问题描述】:
我有一个包含 Person 类对象的列表。我已将列表设置为 ComboBox 的数据源。现在,当我将 ComboBox 的 SelectedItem 设置为 Person 类的新实例时,SelectedItem 永远不会设置。为什么会这样?
public class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}
public string Name { get; set; }
public int Age { get; set; }
}
public List<Person> lstPerson = new List<Person>();
private void Form1_Load(object sender, EventArgs e)
{
lstPerson.Add(new Person("Name1",1));
lstPerson.Add(new Person("Name2",2));
comboBox1.DataSource = lstPerson;
comboBox1.DisplayMember = "Name";
comboBox1.SelectedItem = lstPerson[1]; //If I put this line then it works
//comboBox1.SelectedItem = new Person("Name2", 2); // Not working if I put this line. How can I make this possible?
}
我应该怎么做才能让这段代码正常工作?我在很多论坛上都问过这个问题。从来没有得到任何解决方案。
【问题讨论】:
标签: c# data-binding combobox datasource selecteditem