2010-09-03 78 views
0

我有一個列表與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? 
    } 

我該怎麼做才能讓這段代碼起作用?我在很多論壇都問過這個問題。從來沒有任何解決方案

回答

0

ComboBox類使用IndexOf方法搜索指定的對象。此方法使用Equals方法來確定相等性。

你可以在你重載Equals(obj對象)Person對象,以實現自己的目標

+0

組合框將嘗試匹配與實際在其DataSource存在一些指定的值。 Overriding Equals不會讓你得到任何地方。 – devnull 2010-09-03 09:06:08

+0

是的,你是對的,但注意Rajeesh只想選擇他的問題中的第二項(「Name2」,2)已存在於他的DataSource – Hiber 2010-09-03 09:10:17

+0

好的。非常感謝你的答覆。讓我看看。 – Rajeesh 2010-09-09 11:11:06

相關問題