因为ComboxItem是Object对象,而控件自身没有Value属性.所以,需要自定义一个类,用其对象来存储Text,Value.
public class ComboxItem
{
public string Text = "";
public string Value = "";
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;
最好将string[] x={"aaa","bbb","ccc","ddd","eee"};变成一个集合来绑定到Combobox里。
DataTable dt = new DataTable();
dt.Columns.Add("Value");
dt.Columns.Add("Name");
DataRow dr;
dr = dt.NewRow();
dr[0] = "0";
dr[1] = "aaa";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "1";
dr[1] = "bbb";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "2";
dr[1] = "ccc";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "3";
dr[1] = "ddd";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "4";
dr[1] = "eee";
dt.Rows.Add(dr);
combobox2.ValueMember = "Value";
combobox2.DisplayMember = "Name";
combobox2.DataSource = dt;
combobox2.DropDownStyle = ComboBoxStyle.DropDownList;//设置combobox2的样式
public class ComboBoxItem
{
private string _text=null;
private object _value=null;
public string Text{get{return this._text;} set{this._text=value;}}
public object Value{get {return this._value;} set{this._value=value;}}
public override string ToString()
{
return this._text;
}
}
这段代码我是从网上找的,然后使用
ComboBoxItem newItem = new ComboBoxItem();
newItem.Text = “abc”;
newItem.Value = “1”;
ComboBox1.Items.Add(newItem);
取值使用方法:
ComboBoxItem myItem = (ComboBoxItem)ComboBox1.Items[0];
string strValue = myItem.Value;
你可以用循环 读取数组里面的每个元素 在逐个添加进combobox