在C#中使用ComboBox控件顯示值和參數(shù)有幾種常用的方法:
// 假設(shè)有一個包含值和參數(shù)的數(shù)據(jù)源
List<KeyValuePair<string, int>> data = new List<KeyValuePair<string, int>>
{
new KeyValuePair<string, int>("Value1", 1),
new KeyValuePair<string, int>("Value2", 2),
new KeyValuePair<string, int>("Value3", 3)
};
// 綁定數(shù)據(jù)源
comboBox.DataSource = data;
// 設(shè)置顯示值和參數(shù)的字段名
comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
comboBox.Items.Add(new KeyValuePair<string, int>("Value1", 1));
comboBox.Items.Add(new KeyValuePair<string, int>("Value2", 2));
comboBox.Items.Add(new KeyValuePair<string, int>("Value3", 3));
// 獲取選中項的參數(shù)值
int param = ((KeyValuePair<string, int>)comboBox.SelectedItem).Value;
public class CustomItem
{
public string DisplayValue { get; set; }
public int ParamValue { get; set; }
public override string ToString()
{
return DisplayValue;
}
}
// 創(chuàng)建自定義類的集合
List<CustomItem> items = new List<CustomItem>
{
new CustomItem { DisplayValue = "Value1", ParamValue = 1 },
new CustomItem { DisplayValue = "Value2", ParamValue = 2 },
new CustomItem { DisplayValue = "Value3", ParamValue = 3 }
};
// 綁定數(shù)據(jù)源
comboBox.DataSource = items;
comboBox.DisplayMember = "DisplayValue";
comboBox.ValueMember = "ParamValue";
以上是幾種常用的方法來在C#中使用ComboBox控件顯示值和參數(shù),可以根據(jù)具體需求選擇合適的方式來實現(xiàn)。