使这更简单的一种方法是通过数据绑定。
假设您有一个设备对象:
public class Appliance
{
public string Make { get; set; }
public string ApplianceType { get; set; }
public string Model { get; set; }
public double Price { get; set; }
public string Info { get; set; }
public string ShowString
{
get { return String.Format("{0} {1}", Make, ApplianceType); }
}
}
并且您想将这些列表绑定到组合框。您可以定义组合框中显示的属性并将所选对象转换回类:
List<Appliance> appliances = new List<Appliance>();
// populate list; for example:
appliances.Add(new Appliance
{
Make = "Whirlpool",
ApplianceType = "Fridge",
Model = "WP-300",
Price = 500.00,
Info = "Cools to 4C!"
});
appliances.Add(new Appliance
{
Make = "Maytag",
ApplianceType = "Dishwasher",
Model = "MT-80A",
Price = 400.00,
Info = "Washes spot free!"
});
cmbApplianceList.DataSource = appliances;
cmbApplianceList.DisplayMember = "ShowString";
(ValueMember
您还可以将其绑定到唯一属性。)
当有人在组合框中选择一个项目时,您可以执行以下操作来对选定的类进行操作:
cmbApplianceList_SelectedIndexChanged(object sender, EventArgs e)
{
Appliance selectedAppliance = (Appliance)cmbApplianceList.SelectedItem;
MessageBox.Show(selectedAppliance.Info);
}
在这种情况下,一个消息框会显示Info
所选设备的属性。