ComboBox列表自定义类保存数据

之前没弄明白ComboBox还可以这样用。

先建一个ComboBox子项类,然后可以获取该项类做一些判断,关键是要重写ToString()方法。

    public class ComboItem
    {
        public string text;
        public string value;
        public override string ToString()
        {
            return text;
        }
    }

添加到ComboBox中:

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] strtextarr = { "A", "B", "C" };
            string[] strvaluearr = { "1", "2", "3" };
            int intcount = strtextarr.Length;
            for (int i = 0; i < intcount; i++)
            {
                ComboItem item = new ComboItem();
                item.text = strtextarr[i];
                item.value = strvaluearr[i];
                this.comboBox1.Items.Add(item);
                if (strvaluearr[i] == "1")
                    this.comboBox1.SelectedItem = item;
            }
        }

在ComboBox选择事件中显示选择值到TextBox中:

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboItem item = (ComboItem)this.comboBox1.SelectedItem;
            this.textBox1.Text = item.value;
        }

 

示例下载地址:https://files.cnblogs.com/qiu2013/ComboxCustomItem.zip

 

posted on 2014-05-06 22:33  qiu2013  阅读(1100)  评论(0编辑  收藏  举报

导航