简体   繁体   English

如何使用列表中不可用的项目设置列表绑定组合框的SelectedValue

[英]How to set SelectedValue of a List bound Combobox with an item not available in the List

I have a List with objects of class Person. 我有一个包含类Person的对象的列表。 I have set the list as a DataSource of a ComboBox. 我已将列表设置为ComboBox的数据源。 Now when I set the SelectedItem of the ComboBox a new instance of class Person, the SelectedItem never sets. 现在,当我将ComboBox的SelectedItem设置为Person类的新实例时,SelectedItem永远不会设置。 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. 从来没有任何解决方案。

The ComboBox class searches for the specified object by using the IndexOf method. ComboBox类使用IndexOf方法搜索指定的对象。 This method uses the Equals method to determine equality. 此方法使用Equals方法确定相等性。

you can override Equals(object obj) on you Person object to achieve your goal 您可以在Person对象上重写Equals(object obj)以实现您的目标

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM