winform中的ComboBox不能像webform中的dropdownlist控件一样,在属性中可以同时设置text和value值,可以通过编写一个新类来实现这个功能。
1、首先在form1中添加一个新类ComboBoxItem:
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;
}
}
2、在Form1_Load函数中添加:
ComboBoxItem newitem = new ComboBoxItem();
newitem.Text = "abc";
newitem.Value = "1";
comboBox1.Items.Add(newitem);
3、在comboBox1_SelectedIndexChanged中添加:
ComboBoxItem myItem = (ComboBoxItem)comboBox1.Items[comboBox1.SelectedIndex];
MessageBox.Show(myItem.Value.ToString());
就可以看到输出效果了!!!
楼上正解,我在项目中也用到了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
/// <summary>
/// ComboBox的Item
/// </summary>
public class TextValue
{
public TextValue() { }
public TextValue( string inText, int inValue)
{
this .Text = inText;
this .Value = inValue;
}
private string _text;
private int _value;
/// <summary>
/// 文本
/// </summary>
public string Text
{
set { this ._text = value; }
get { return this ._text; }
}
/// <summary>
/// 值
/// </summary>
public int Value
{
set { this ._value = value; }
get { return this ._value; }
}
}
public partial class TempLateWave : Form
{ List<TextValue> PurposeList = new List<TextValue>();
public TempLateWave()
{
InitializeComponent();
PurposeList.Add( new TextValue( "精度" , 0));
PurposeList.Add( new TextValue( "线性度" , 1));
PurposeList.Add( new TextValue( "一致性" , 2));
cbx.DataSource = PurposeList; //cbx 就是ComboBox控件
cbx.DisplayMember = "Text" ;
cbx.ValueMember = "Value" ;
}
} |