2011-03-29 57 views
5


我類的幾個對象:的ComboBox數據綁定引起的ArgumentException

class Person 
{ 
    public string Name { get; set; } 
    public string Sex { get; set; } 
    public int Age { get; set; } 

    public override string ToString() 
    { 
     return Name + "; " + Sex + "; " + Age; 
    } 
} 

和具有Person類型的屬性的類:

class Cl 
{ 
    public Person Person { get; set; } 
} 

我要綁定Cl.Person到組合框。當我嘗試這樣做時:

Cl cl = new cl(); 
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}}; 
comboBox.DataBindings.Add("Item", cl, "Person"); 

我收到一個ArgumentException。我應該如何修改綁定以獲得正確的程序行爲?
在此先感謝!

回答

7

綁定到「的SelectedItem」:

 var persons = new List<Person> { new Person() { Name = "John Doe"}, new Person() { Name = "Scott Tiger" }}; 
     comboBox1.DisplayMember = "Name"; 
     comboBox1.DataSource = persons; 
     comboBox1.DataBindings.Add("SelectedItem", cl, "Person"); 
1

嘗試

comboBox.DataBindings.Add("Text", cl, "Person.Name"); 

代替

你需要告訴你要綁定哪個屬性就可以了組合框的哪個屬性在對象上(它的Text屬性,在我的例子,這將顯示名稱被選人的財產)。

* 編輯: *實際上報廢了,我感到困惑。你幾乎擁有它,只有組合框沒有按;噸有一個屬性叫做項目,你想要的SelectedItem代替,就像這樣:

Cl cl = new cl(); 
comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}}; 
comboBox.DataBindings.Add("SelectedItem", cl, "Person"); 
+0

我希望combobox包含人而不是他們的名字。 – StuffHappens 2011-03-29 12:15:00

+0

@StuffHappens:是的,他們會但無視這一點,看看我的更新 – w69rdy 2011-03-29 12:21:01

3

對於簡單的數據綁定,這將工作

cl.Person = new Person{ Name="Harold" }; 
comboBox.DataBindings.Add("Text",cl.Person, "Name"); 

但我不認爲這就是你想要的。我想你想綁定到一個項目列表,然後選擇一個。要結合項目的列表和顯示名稱屬性,嘗試這個辦法:

comboBox.DataSource = new List<Person> {new Person{Name = "1"}, new Person{Name = "2"}}; 
comboBox.DisplayMember = "Name"; 

前提是你的Person類的equals(),這樣,比如說,一個人等於另一個,如果它們具有相同的名稱,然後綁定到SelectedItem屬性會像這樣:

Cl cl = new Cl {Person = new Person {Name="2" }}; 
comboBox.DataBindings.Add("SelectedItem", cl, "Person"); 

如果您不能覆蓋equals()方法,那麼你只需要確保你引用從數據源列表中選擇一個Person實例,所以下面的代碼適用於您的特定代碼:

Cl cl = new Cl(); 
cl.Person = ((List<Person>)comboBox1.DataSource)[1]; 
comboBox.DataBindings.Add("SelectedItem", cl, "Person"); 
0

如果您使用枚舉可能是u有一類枚舉的,你可以這樣

  1. 組合框指定組合框datasourse如

    comboBoxname.DataSource = Enum.GetValues(typeof(your enum)); 
    
  2. 現在讓我們結合COMBOX箱,因爲我們有數據源

    comboBoxname.DataBindings.Add("SelectedItem", 
               object, 
               "field of type enum in the object");