星期日, 11月 06, 2016

[C#] ComboBox 預設值

要指定 ComboBox Item 中的選項(Item),要透過指定 ComboBox.SelectedIndex 來做到

簡易範例
namespace ComboBoxDefaultValue
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("A");
            comboBox1.Items.Add("B");
            comboBox1.Items.Add("O");
            comboBox1.Items.Add("AB");

            // ComboBox 預設顯示值為 O
            comboBox1.SelectedIndex = 2;
        }

        private void btnAssign_Click(object sender, EventArgs e)
        {
            // 指定顯示 AB
            comboBox1.SelectedIndex = comboBox1.FindStringExact("AB");
        }

        private void btnEmpty_Click(object sender, EventArgs e)
        {
            // ComboBox 不顯示任何資料
            comboBox1.SelectedIndex = -1;
        }

        private void btnExt_Click(object sender, EventArgs e)
        {
            // 指定顯示 Item,不存在就顯示第一個 Item
            comboBox1.SelectedIndex = comboBox1.FindStringExactDefault("AA");
        }
    }

    /// <summary>
    /// ComboBox 擴充方法
    /// </summary>
    public static class ExtComboBox
    {
        /// <summary>
        /// 利用 FindStringExtra() 搜尋,沒有該 Item 的話,就回傳 Index = 0,而非 -1
        /// </summary>
        /// <param name="cbo">ComboBox 控件</param>
        /// <param name="target">目標搜尋字串</param>
        /// <returns>該 Item 索引</returns>
        public static int FindStringExactDefault(this ComboBox cbo, string target)
        {
            int index = cbo.FindStringExact(target);
            return index == -1 ? 0 : index;
        }
    }
}
[C#] ComboBox 預設值

沒有留言:

張貼留言