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.