views:

69

answers:

1

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.

A: 

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

Hiber
The ComboBox will try to match the value specified with something that actually exists in its DataSource. Overriding Equals won't get you anywhere.
devnull
yes, you are right, but notice that Rajeesh just want to select the second item in his question, ("Name2", 2) already existing in his DataSource
Hiber
Ok. Thank you very much for the reply. Let me look into that.
Rajeesh