您想轻松检索所选项目中的数据吗?我更喜欢用它的特殊类型填充数据,以便可以直接从选定的项目中获取数据。因为这个Combox.Item.Add()
函数需要一个Object类型的参数,所以,我建议你可以先定义一个新类型的数据,像这样:
/// <summary>
/// my own data define
/// </summary>
public class MyFloor
{
public int ID { get; set; }
public string Name { get; set; }
public string Floor { get; set; }
//very important, the result will be displayed in the combox
public override string ToString()
{
return string.Format("{0}->{1}->{2}", ID, Name, Floor);
}
}
然后,您可以将数据填充到特殊类型的组合框中:
void FillData()
{
//load data from txt or database
List<MyFloor> floorList = new List<MyFloor>(){
new MyFloor{ID=1, Name="store1", Floor="1"},
new MyFloor{ID=2, Name="store2", Floor="1"},
new MyFloor{ID=3, Name="store2", Floor="2"},
new MyFloor{ID=4, Name="store2", Floor="3"},
new MyFloor{ID=5, Name="store3", Floor="2"}
};
//fill into combox
foreach (MyFloor floor in floorList)
{
this.comboBox1.Items.Add(floor);
}
}
最后,您可以直接获取数据:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//retrieve data from selected item as MyFloor object
MyFloor floor = this.comboBox1.SelectedItem as MyFloor;
//show the selected data object
if (floor != null)
{
txtID.Text = floor.ID.ToString();
txtName.Text = floor.Name;
txtFloor.Text = floor.Floor;
}
}
这是我的结果: