[英]Binding a List To a comboBox
I have a List of Person
objects (which is loaded from the database), I call it PersonList
. 我有一个
Person
对象列表(从数据库中加载),我称它为PersonList
。 Person
class has four attributes Person_Id(PK)
, Name
, Family
and Address
. Person
类具有四个属性Person_Id(PK)
, Name
, Family
和Address
。
I want to bind the context of this list to a ComboBox
. 我想将此列表的上下文绑定到
ComboBox
。 Also I want to show both Name
and Family
of each person in ComboBox (not the Person_Id
or Address
). 我也想在ComboBox中显示每个人的
Name
和Family
(而不是Person_Id
或Address
)。 On the other hand I want to gain Person_Id(PK) of the selected value of ComboBox if the end user selects anyone. 另一方面,如果最终用户选择任何人,我想获得ComboBox所选值的Person_Id(PK)。
How can I manage to do this? 我该如何做到这一点? Also I'm wondering if I delete any items of
PersonList
the ComboBox updates automatically or I Should update manually by myself? 此外,我想知道是否要删除
PersonList
的任何项目,而ComboBox会自动更新,还是应该由我自己手动更新?
Add to your Person class a readonly property that returns the string desired 向您的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);
}
}
now assign the property DisplayMember
of the combobox to the read only property and the ValueMember property to the Person_ID of the class Person. 现在,将组合框的
DisplayMember
属性分配给只读属性,并将ValueMember属性分配给Person类的Person_ID。
comboBox1.DataSource = PersonList;
comboBox1.DisplayMember = "name_family";
comboBox1.ValueMember = "id";
Now in the combobox SelectedIndexChange
event you could retrieve the ID from the SelectedItemValue 现在,在组合框
SelectedIndexChange
事件中,您可以从SelectedItemValue中检索ID。
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(comboBox1.SelectedValue != null)
{
int personID = Convert.ToInt32(comboBox1.SelectedValue);
.......
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.