星期三, 8月 26, 2015

[C#] ComboBox 多欄位 - DrawItem

利用 ComboBox DrawItem Event 來作到多欄位顯示功能

DateSelect Class
namespace ComboBoxMultiCols
{
    public class DateSelect
    {
        public int Year { get; set; }
        public int TWYear { get; set; }

        public static List<DateSelect> DataFill()
        {
            List<DateSelect> result = new List<DateSelect>();

            DateTime 
                Today = DateTime.Today ,
                LoopDate = DateTime.Today ;
            int 
                Year = 0 ,
                TWYear = 0;
   
            System.Globalization.TaiwanCalendar tc = new System.Globalization.TaiwanCalendar();

            for (int i = 0; i < 10; i++)
            {
    
                LoopDate = Today.AddYears(i * -1);
                Year = LoopDate.Year;
                TWYear = tc.GetYear(LoopDate);

                DateSelect ds = new DateSelect()
                {
                    Year = Year ,
                    TWYear = TWYear
                };

                result.Add(ds);
            }

            return result;
        }
    }
}
WinForm Demo
namespace ComboBoxMultiCols
{
    public partial class MultiCols_DrawItem : Form
    {
        public MultiCols_DrawItem()
        {
            InitializeComponent();
        }

        private void MultiCols_DrawItem_Load(object sender, EventArgs e)
        {
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.DataSource = DateSelect.DataFill();
            comboBox1.DisplayMember = "Year";
            comboBox1.ValueMember = "TWYear";

            comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            comboBox1.DrawItem += comboBox1_DrawItem;
        }

        void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 繪製預設背景
            e.DrawBackground();

            // DataSource 是 List<DateSelect>,所以這裡必須轉型為 DateSelect
            // 假如 DataSource 是 DataTable,就必須轉型為 DataRowView
            DateSelect ds = (DateSelect)this.comboBox1.Items[e.Index];

            // ComboBox 內文字
            string DropDownInfo = string.Format("{0} (民國 {1:000} 年)", ds.Year, ds.TWYear);

            // 取得 ComboBox 界限
            Rectangle rec = e.Bounds;
   
            // 把文字繪進去
            using (SolidBrush sb = new SolidBrush(e.ForeColor))
            {
                e.Graphics.DrawString(DropDownInfo, e.Font, sb, rec);
            }
        }
    }
}

[C#] ComboBox 多欄位 - DrawItem-1

這篇是參考官方範例 How to create a multiple-column drop-down list for a combo box in Windows Forms 來撰寫,原本以為可以達到論壇問題需求 - 下拉選單內文字內容維持單值,但下拉選項要有輔助資訊,執行官方範例有看見該需求的效果,但實際練習時才發現到,原來要在 DropDownStyle = ComboBoxStyle.DropDown 才會有這樣的效果,美中不足的地方

[C#] ComboBox 多欄位 - DrawItem-2

很好奇為甚麼要有 e.DrawBackground() 這行 Code,沒有不行嗎?拿掉後點選下拉式選項,就會變成下圖

[C#] ComboBox 多欄位 - DrawItem-3

沒有留言:

張貼留言