初学winform的时候,一直以为winform中的combox只能添加简单的仅有text的item,而不象aspx中的listitem那样即有text,又有value,结果很快发现自己错了,以下是一个示例:
先声明一个类
public class ClsItemObject
{
public string ClassName = "", ClassId = "";
public ClsItemObject(string _clsName, string _clsId)
{
ClassName = _clsName;
ClassId = _clsId;
}
public override string ToString()
{
return ClassName;
}
}
利用这个类,我们可以直接在combox中添加复杂类型的item
ClsItemObject[] co = new ClsItemObject[3];
co[0] = new ClsItemObject("精美礼品", "001");
co[1] = new ClsItemObject("--手工礼品", "002");
co[2] = new ClsItemObject("家用电器", "333");
comboBox1.Items.AddRange(co);
comboBox1.SelectedIndex = 1;
取值时,要记得用强制类型转换,转换成正确的类型
ClsItemObject coSelected = (ClsItemObject)comboBox1.SelectedItem;
MessageBox.Show(coSelected.ClassId);
使用一例:
-
public class StringIntObject
-
{
-
public string Text;
-
public int Value;
-
-
public StringIntObject(string text, int value)
-
{
-
Text = text;
-
Value = value;
-
}
-
-
public override string ToString()
-
{
-
return Text;
-
}
-
}
-
-
public void RefreshHubGroup()
-
{
-
this.comboBox3.Items.Clear();
-
CLocalTabStruct.SHubGroupParam[] records = null;
-
CAccessLayer.GetHubGroupParam(out records);
-
if (records == null)
-
return;
-
-
StringIntObject[] so = new StringIntObject[records.Length];
-
for (int i = 0; i records.Length; i++)
-
so[i] = new StringIntObject(records[i].GroupName, records[i].HGPId);
-
this.comboBox3.Items.AddRange(so);
-
this.comboBox3.SelectedIndex = 0;
- }
来自博客:
http://www.cnblogs.com/Caceolod/articles/1008983.html