向您的 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);
}
}
现在将DisplayMember
组合框的属性分配给只读属性,将 ValueMember 属性分配给 Person 类的 Person_ID。
comboBox1.DataSource = PersonList;
comboBox1.DisplayMember = "name_family";
comboBox1.ValueMember = "id";
现在在组合框SelectedIndexChange
事件中,您可以从 SelectedItemValue 中检索 ID
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(comboBox1.SelectedValue != null)
{
int personID = Convert.ToInt32(comboBox1.SelectedValue);
.......
}
}