如何使用列表中不可用的项目设置列表绑定组合框的 SelectedValue
我有一个包含 Person 类对象的列表。我已将列表设置为组合框的数据源。现在,当我将 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?
}
我应该怎么做才能让这段代码正常工作?我在很多论坛上都问过这个问题。一直没有得到任何解决办法。
I have a List with objects of class Person. I have set the list as a DataSource of a ComboBox. Now when I set the SelectedItem of the ComboBox a new instance of class Person, the SelectedItem never sets. Why it happens?
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?
}
What should I do to get this code working? I have asked this question in many forums. Never got any solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ComboBox 类使用 IndexOf 方法搜索指定的对象。此方法使用 Equals 方法来确定相等性。
您可以在 Person 对象上重写 Equals(object obj) 来实现您的目标
The ComboBox class searches for the specified object by using the IndexOf method. This method uses the Equals method to determine equality.
you can override Equals(object obj) on you Person object to achieve your goal