星期五, 1月 04, 2019

[C#] DataBinding 上顯示民國年

之前以為 DataBinding 沒有辦法轉成民國年,最近才發現原來 DataBinding 是可以設定 CultureInfo,筆記測試結果並整合該篇筆記 - [C#] DataGridView 內顯示民國年

Add 多載說明
[C#] DataBinding 上顯示民國年-2

C# Code
namespace DataBinding4TWDate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string FormatString = "yyy/MM/dd";

        private void Form1_Load(object sender, EventArgs e)
        {
            CultureInfo ci = CultureSetting();

            bindingSource1.DataSource = GetData();
            bindingNavigator1.BindingSource = bindingSource1;

            // TextBox 
            txtEmpNO.DataBindings.Add("Text", bindingSource1, "EmpNO");
            txtEmpName.DataBindings.Add("Text", bindingSource1, "EmpName");
            txtHireDate.DataBindings.Add("Text", bindingSource1, "HireDate", true, DataSourceUpdateMode.OnValidation, null, FormatString, ci);

            // DataGridView
            dataGridView1.DataSource = bindingSource1;
            string ColHireDate = "ColHireDate";
            dataGridView1.Columns[ColHireDate].DefaultCellStyle.FormatProvider = ci;
            dataGridView1.Columns[ColHireDate].DefaultCellStyle.Format = FormatString;
        }

        private CultureInfo CultureSetting()
        {
            CultureInfo ci = new CultureInfo("zh-tw");
            TaiwanCalendar tc = new TaiwanCalendar();
            ci.DateTimeFormat.Calendar = tc;
            return ci;
        }

        private List<Employ> GetData()
        {
            var Data = new List<Employ>()
            {
                new Employ(){ EmpNO = "1" , EmpName = "張三" , HireDate = new DateTime(1999,10,3)} ,
                new Employ(){ EmpNO = "2" , EmpName = "李四" , HireDate = new DateTime(2015,7,7)} ,
                new Employ(){ EmpNO = "3" , EmpName = "王五" , HireDate = new DateTime(2017,5,3)} ,
            };
            return Data;
        }
    }

    public class Employ
    {
        public string EmpNO { get; set; }
        public string EmpName { get; set; }
        public DateTime HireDate { get; set; }
    }
}
[C#] DataBinding 上顯示民國年-1

測試 DateTimePicker 時發現該篇-文章,該控件看起來是無法轉成民國年就是,反正本來就沒有使用它,直接跳過

沒有留言:

張貼留言