星期五, 8月 21, 2015

[C#] ComboBox 多欄位 - Format

利用 ComboBox Format 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_Format : Form
    {
        public MultiCols_Format()
        {
            InitializeComponent();
        }

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

        private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
        {
            DateSelect ds = e.ListItem as DateSelect;
            if (ds == null) return;
            e.Value = string.Format("{0} (民國{1})",ds.Year,ds.TWYear.ToString("000"));
        }
    }
}

[C#] ComboBox 多欄位 - Format

沒有留言:

張貼留言