C#中combox怎么显示值和参数
导读:在C#中使用ComboBox控件显示值和参数有几种常用的方法: 使用数据绑定:可以通过设置ComboBox的DataSource属性来绑定数据源,然后设置DisplayMember和ValueMember属性来指定显示值和参数,例如:...
在C#中使用ComboBox控件显示值和参数有几种常用的方法:
- 使用数据绑定:可以通过设置ComboBox的DataSource属性来绑定数据源,然后设置DisplayMember和ValueMember属性来指定显示值和参数,例如:
// 假设有一个包含值和参数的数据源
ListKeyValuePairstring, int>
>
data = new ListKeyValuePairstring, int>
>
{
new KeyValuePairstring, int>
("Value1", 1),
new KeyValuePairstring, int>
("Value2", 2),
new KeyValuePairstring, int>
("Value3", 3)
}
;
// 绑定数据源
comboBox.DataSource = data;
// 设置显示值和参数的字段名
comboBox.DisplayMember = "Key";
comboBox.ValueMember = "Value";
- 手动添加项:可以通过Add方法手动添加每个项,并通过Tag属性设置参数,例如:
comboBox.Items.Add(new KeyValuePairstring, int>
("Value1", 1));
comboBox.Items.Add(new KeyValuePairstring, int>
("Value2", 2));
comboBox.Items.Add(new KeyValuePairstring, int>
("Value3", 3));
// 获取选中项的参数值
int param = ((KeyValuePairstring, int>
)comboBox.SelectedItem).Value;
- 使用自定义类:可以创建一个包含值和参数的自定义类,然后设置ComboBox的DataSource属性为该类的集合,如下所示:
public class CustomItem
{
public string DisplayValue {
get;
set;
}
public int ParamValue {
get;
set;
}
public override string ToString()
{
return DisplayValue;
}
}
// 创建自定义类的集合
ListCustomItem>
items = new ListCustomItem>
{
new CustomItem {
DisplayValue = "Value1", ParamValue = 1 }
,
new CustomItem {
DisplayValue = "Value2", ParamValue = 2 }
,
new CustomItem {
DisplayValue = "Value3", ParamValue = 3 }
}
;
// 绑定数据源
comboBox.DataSource = items;
comboBox.DisplayMember = "DisplayValue";
comboBox.ValueMember = "ParamValue";
以上是几种常用的方法来在C#中使用ComboBox控件显示值和参数,可以根据具体需求选择合适的方式来实现。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C#中combox怎么显示值和参数
本文地址: https://pptw.com/jishu/648893.html