做个同时带Text和Value的ComboBox

    技术2022-05-11  71

     

    .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());        }    }} 


    最新回复(0)