星期三, 11月 09, 2016

[C#] DataGridView 內顯示民國年

在 DataGridView 內透過 Taiwan Calendar 來把西元年轉換為民國年
namespace dgvDate
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;

            // 建立 Column
            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Data",
                Name = "ColAD",
                HeaderText = "西元年",
                Width = 100
            });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Data",
                Name = "ColSimple",
                HeaderText = "民國年 - 簡單",
                Width = 100
            });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Data",
                Name = "ColFull",
                HeaderText = "民國年 - 完整",
                Width = 100
            });

            dataGridView1.Columns.Add(new DataGridViewTextBoxColumn
            {
                DataPropertyName = "Data",
                Name = "ColCustom",
                HeaderText = "民國年 - 自訂",
                Width = 100
            });

            // 資料來源
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Data", typeof(DateTime));
            dt.Rows.Add(1, DateTime.Today);
            dataGridView1.DataSource = dt;

            // 民國年設定
            CultureInfo ci = new CultureInfo("zh-TW", true);
            ci.DateTimeFormat.Calendar = new TaiwanCalendar();

            dataGridView1.Columns["ColSimple"].DefaultCellStyle.FormatProvider = ci;
            dataGridView1.Columns["ColSimple"].DefaultCellStyle.Format = "d";

            dataGridView1.Columns["ColFull"].DefaultCellStyle.FormatProvider = ci;
            dataGridView1.Columns["ColFull"].DefaultCellStyle.Format = "D";

            dataGridView1.Columns["ColCustom"].DefaultCellStyle.FormatProvider = ci;
            dataGridView1.Columns["ColCustom"].DefaultCellStyle.Format = "yyy-MM-dd";
        }
    }
}
[C#] DataGridView 內顯示民國年

沒有留言:

張貼留言