利用DataSource讓ComboBox有不同的顯示與選取值

摘要:利用DataSource讓ComboBox有不同的顯示與選取值


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

namespace ComboBoxDataSource
{
    public partial class Form1 : Form
    {
        class UserData
        {
            private string name;
            private string id;

            public UserData(string Name, string Id)
            {
                name = Name;
                id = Id;
            }

            public string Name
            { get { return name; } }
            public string Id
            { get { return id; } }
        }

        public Form1()
        {
            InitializeComponent();
            SetItems();
            this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged);
        }

        private void SetItems()
        {
            ArrayList al = new ArrayList();
            al.Add(new UserData("Name1", "Id1"));
            al.Add(new UserData("Name2", "Id2"));
            al.Add(new UserData("Name3", "Id3"));
            al.Add(new UserData("Name4", "Id4"));
            comboBox1.DataSource = al;
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "Id";
        }

        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.Text = String.Format("{0}", comboBox1.SelectedValue);
        }
    }

}

 

 

程式下載:
http://cid-0ce1062ddca3c8bc.office.live.com/embedicon.aspx/%e5%85%ac%e9%96%8b/ComboBoxDataSource.zip