2013-07-27 83 views
1

我有如下的類:填充組合框

class villages { public string name; public int pId; }

我用它在我的形式是這樣的:

private villages[] centerVillage=new villages[]{ 
     new villages{name= "village1",pId=0}, 
     new villages{name= "village2",pId=1}, 
     new villages{name= "village3",pId=2}, 
     new villages{name= "village4",pId=3}, 
     new villages{name= "village5",pId=4}, 
     new villages{name= "village6",pId=5}, 
     new villages{name= "village7",pId=6}, 
    }; 

現在我要填補我combobox1villages[]那它的DisplayMember=namevalueMember=pId

我已經試過這個,但不起作用。

combobox1.DataSource = new BindingSource(centerVillage, null); 
combobox1.DisplayMember = "name"; 
combobox1.ValueMember = "pId"; 

回答

3

在您需要定義屬性來公開的值村莊類,它不與歸檔成員的工作:

// Exceptions: 
    // System.ArgumentException: 
    //  The specified property cannot be found on the object specified by the System.Windows.Forms.ListControl.DataSource 
    //  property. 
    public string ValueMember { get; set; } 

這將解決這個問題:

class villages 
    { 
     public string name { get; set; } 
     public int pId { get; set; } 
    } 
+0

@ user1592474所有你需要做的就是改變你的課程以匹配他的課程。你的代碼的其餘部分應該正常工作。並將您的comboBox1.DataSource更改爲中心菜單。 –

+0

謝謝我也像這樣實現它:combobox1.DataSource = new BindingSource(centerVillage,null); combobox1.DisplayMember =「name」; combobox1.ValueMember =「pId」; –

+1

像馬克說的,你不需要BindingSource這個,你可以簡單地將centerVillage數組設置爲DataSource –

1
combobox1.DataSource = villages; 
combobox.DisplayMember = "name"; 
combobox1.ValueMember = "pId";