最近在项目中用到ComboBox,发现其没有value属性,这样存值时很不方便
于时找到以下办法来解决,有需要的可以看一下
我使用一个结构体添加到Items中来扩充Items属性,这样其就可以有value值了
public override string ToString()//重写此方法使ComboBox显示文本
{
return this.text;
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
//添加项
for (int i = 0; i <= 10; i++)
{
ComboItem item = new ComboItem("文本" + i, "值" + i);
comboBox1.Items.Add(item);
}
}
private void button1_Click(object sender, EventArgs e)
{
//取值,这里要判断一个SelectedItem是否为空
ComboItem selectItem = (ComboItem)comboBox1.SelectedItem;
MessageBox.Show(selectItem.text+" | "+selectItem.value);
}
}