comboBox获取value中的值
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { string a = ((ComboBoxItem)comboBox2.SelectedItem).Value; textBox2.Text = a; } private void Form1_Load(object sender, EventArgs e) { ComboBoxItem i1 = new ComboBoxItem(); i1.Text = "this is i1"; i1.Value = "001"; ComboBoxItem i2 = new ComboBoxItem(); i2.Text = "this is i2"; i2.Value = "002"; comboBox2.Items.Add(i1); comboBox2.Items.Add(i2);
comboBox2.DisplayMember = "text";
comboBox2.ValueMember = "value"; } public class ComboBoxItem { private string m_Text; private string m_Value; public ComboBoxItem() { this.m_Text = String.Empty; this.m_Value = String.Empty; } public string Text { get { return this.m_Text; } set { this.m_Text = value; } } public string Value { get { return this.m_Value; } set { this.m_Value = value; } } public override string ToString() { return this.m_Text; //最关键的 } }
ComboBox的Items不能添加Value
不想用绑定的话,自已写一个实现Value和Text属性的类,然后重写ToString()方法,并返回和Text属性一样的值,然后把这个类的实际Add到ComboBox.Items中,取值时再转换一下类型.
当你往ComboxBox的Item中扔一个任意object时,显示出的内容就是这个object的ToString()方法.所以必须重写ToString()方法,来显示你要显示的内容.