2013-05-11 105 views
0

我有一个列表Person对象(从数据库加载),我把它称为PersonListPerson类有四个属性Person_Id(PK),Name,FamilyAddress将列表绑定到组合框

我想将此列表的上下文绑定到ComboBox。我还想在组合框中显示每个人的NameFamily(不是Person_IdAddress)。另一方面,如果最终用户选择任何人,我想获得ComboBox的选定值的Person_Id(PK)。

我该如何设法做到这一点?此外,我想知道如果我删除任何项目的PersonList组合框自动更新或我应该自己手动更新?

回答

0

添加到您的Person类返回预期

class Person 
{ 
    public int Person_ID {get;set;} 
    public string name {get;set;} 
    public string family {get;set;} 
    public int address {get;set;} 
    public string name_family { get {return this.ToString();}} 

    public override string ToString() 
    { 
     return string.Format("{0} {1}", this.name, this.family); 
    } 
} 

现在分配组合框的只读属性和ValueMember属性类Person的PERSON_ID的财产DisplayMember字符串只读属性。

comboBox1.DataSource = PersonList; 
comboBox1.DisplayMember = "name_family"; 
comboBox1.ValueMember = "id"; 

现在在ComboBox SelectedIndexChange事件中,你可以检索从SelectedItemValue

private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e) 
{ 
    if(comboBox1.SelectedValue != null) 
    { 
     int personID = Convert.ToInt32(comboBox1.SelectedValue); 
     ....... 
    } 
} 
+0

谢谢你的答案ID,但仍然没有解决一个问题?如果我通过单击这个工作来放置一个按钮:PersonList.RemoveAt(0);如果没有进一步的编程,我不想看到comboBox的第一项。可能吗? – user2373198 2013-05-11 19:50:16