区块链系统之家

关注最新技术动态

C# Combobox如何设置ComboxItem的value

因为ComboxItem是Object对象,而控件自身没有Value属性.所以,需要自定义一个类,用其对象来存储Text,Value.
public class ComboxItem
{
public string Text {get; set;}
public string Value {get; set;}

public ComboxItem(string _Text, string _Value)
{
Text = _Text;
Value = _Value;
}
public override string ToString()
{
return Text;
}
}
赋值 如下:
combobox2.Items.Add(New ComboxItem("Text1", "Value1"));
combobox2.Items.Add(New ComboxItem("Text2", "Value2"));
combobox2.Items.Add(New ComboxItem("Text3", "Value3"));
或者:
ComboxItem[] x = {
new ComboxItem("Text1", "Value1"),
new ComboxItem("Text2", "Value2"),
new ComboxItem("Text3", "Value1")
};
combobox2.Items.AddRange(x);

取值时需要转换一下 如下:
string str = ((ComboxItem)combobox2.Items[0]).Value;
这个转换和你直接为Combobox控件绑定数据源是一样的.
如果你是这么绑定的数据
combobox2.DataSource = ds.Tables(0);//ds是dataset
combobox2.DisplayMember = "TextCol";
combobox2.ValueMember = "ValueCol";
那么得这么取值
string str = ((System.Data.DataRowView)combobox2.Items[0])("ValueCol").ToString;

posted on 2012-12-20 17:16  新技术动态  阅读(2948)  评论(0编辑  收藏  举报

导航