如何设置Selected列表的SelectedValue列表中的项目不可用列表
问题描述:
我有一个列表与Person类的对象。我已将列表设置为ComboBox的DataSource。现在,当我将ComboBox的SelectedItem设置为Person类的新实例时,SelectedItem从不设置。为什么会发生?如何设置Selected列表的SelectedValue列表中的项目不可用列表
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?
}
我该怎么做才能让这段代码起作用?我在很多论坛都问过这个问题。从来没有任何解决方案
答
ComboBox类使用IndexOf方法搜索指定的对象。此方法使用Equals方法来确定相等性。
你可以在你重载Equals(obj对象)Person对象,以实现自己的目标
组合框将尝试匹配与实际在其DataSource存在一些指定的值。 Overriding Equals不会让你得到任何地方。 – devnull 2010-09-03 09:06:08
是的,你是对的,但注意Rajeesh只想选择他的问题中的第二项(“Name2”,2)已存在于他的DataSource – Hiber 2010-09-03 09:10:17
好的。非常感谢你的答复。让我看看。 – Rajeesh 2010-09-09 11:11:06