C# - 使用 List<T> 為 ComboBox 加入 Item

摘要:C# - 使用 List 為 ComboBox 加入 Item

在 WinForm 中,使用工具的方式對 ComboBox 填入值,不是我所預期的作法,因為我所想的 ComboBox 應該要是如同 DropDownList 一樣;但我錯了,之後上網找了一下,找到了 小歐 寫的這篇「ComboBox 新增 Item 時具有 Text 與 Value 」後才發現,原來是要這樣用,只可惜我的資料很少,不太需要用到 DataTable 的方式。之後想到了用 List<T> 來試一試...嗯嗯嗯,也達到了不錯的效果,以下就來實作一下...

步驟一:設計一下畫面


步驟二:開始撰寫程式碼

Code:

namespace WinForm_Directory
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public class cboDataList
        {
            public string cbo_Name { get; set; }
            public string cbo_Value { get; set; }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<cboDataList> lis_DataList = new List<cboDataList>()
            {
                new cboDataList
                {
                    cbo_Name = "小呆",
                    cbo_Value = "Danny"                   
                },
                new cboDataList
                {
                    cbo_Name = "傻婆",
                    cbo_Value = "Peggy"                   
                },
                new cboDataList
                {
                    cbo_Name = "哪位",
                    cbo_Value = "Who"                   
                }
            };

            comboBox1.DataSource = lis_DataList;
            comboBox1.DisplayMember = "cbo_Name";
            comboBox1.ValueMember = "cbo_Value";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(comboBox1.Text + "===" + comboBox1.SelectedValue);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> di_ChkData = new Dictionary<string, string>();

            di_ChkData.Add("Danny", "小呆");
            di_ChkData.Add("Peggy", "傻婆");

            if (di_ChkData.ContainsKey(comboBox1.SelectedValue.ToString()))
                MessageBox.Show(di_ChkData[comboBox1.SelectedValue.ToString()] + ":我有在唷!!!");
            else
                MessageBox.Show("你哪位!?");
        }
    }
}

結果:




參考:
[C#][VB.NET] ComboBox 新增 Item 時具有 Text 與 Value