2013-07-27 194 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";