1. 程式人生 > >做個同時帶Text和Value的ComboBox

做個同時帶Text和Value的ComboBox

this.combobox.selectIndex=0;

NET 2.0 Web控制元件的ComboBox就比WinForm的ComboBox好,可以同時儲存顯示值和實際值。這個很重要,比如有個下拉框選擇工作人員,顯示的是姓名,實際交給系統處理是工號。

以前都是特地用個DataTable輔助的,比較麻煩。首先複製DataTable裡的每一行的某個欄位(比如姓名)到ComboBox的每一項,然後在comboBox1_SelectedIndexChanged事件裡,得到當前的ItemIndex,回過頭去找DataTable.Rows[該ItemIndex]["工號"].ToString()

這樣做不是不可以,但總歸感覺很怪。今天發現原來還有別的方式可以實現。

首先定義一個類(定義完了就不用去管它了,一直可以用)

using System;
using System.Collections.Generic;
using System.Text;

namespace AboutComboBox
{
    class TextAndValue
    {
        private string _RealValue = "";
        private string _DisplayText = "";

        public string DisplayText
        {
            get
            {
                return _DisplayText;
            }
        }

        public string RealValue
        {
            get
            {
                return _RealValue;
            }
        }

        public TextAndValue(string ShowText, string RealVal)
        {
            _DisplayText = ShowText;
            _RealValue = RealVal;
        }

        public override string ToString()
        {
            return _RealValue.ToString();
        }

    }
}

使用時,先製造一個ArrayList,然後繫結到ComboBox。選擇時,簡單呼叫comboBox1.SelectedValue.ToString()就行了!

程式碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AboutComboBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private static DataSet ds = new DataSet();

        private void Form1_Load(object sender, EventArgs e)
        {
           
            ArrayList al = new ArrayList();
            al.Add(new TextAndValue("張三","zs10111"));
            al.Add(new TextAndValue("李四", "ls10253"));
            al.Add(new TextAndValue("阿拉蕾", "A20876"));

            comboBox1.DataSource = al;
            comboBox1.DisplayMember = "DisplayText";
            comboBox1.ValueMember = "RealValue";

            ArrayList al2 = new ArrayList();
            al2.Add(new TextAndValue("火腿", "9601101"));
            al2.Add(new TextAndValue("肉鬆", "9601202"));

            comboBox2.DataSource = al2;
            comboBox2.DisplayMember = "DisplayText";
            comboBox2.ValueMember = "RealValue";

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(comboBox1.SelectedValue.ToString());
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            //MessageBox.Show(comboBox2.SelectedValue.ToString());
        }
    }
}