Skip to main content
 首页 » 编程设计

c#之从结构数组填充组合框

2024年02月13日13jirigala

我有一个类如下:

类村庄 { 公共(public)字符串名称; 公共(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}, 
    }; 

现在我想从 villages[] 中填充我的 combobox1,它的 DisplayMember=name 和 valueMember=pId

我已经试过了,但是没有用。

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

请您参考如下方法:

在 villages 类中,您必须定义属性来公开值,它不适用于已归档的成员:

    // 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; } 
    }