2017/02/14

C#.Net 將Class資料透過List繫結到DataGridView

其實這篇好久以前就可以寫了
只是不知道為什麼一直沒有寫XDDDD

執行結果:



Code:
using System.Collections.Generic;
using System.Windows.Forms;

namespace Post
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// DataGridView
        /// </summary>
        private DataGridView dgv = new DataGridView();

        /// <summary>
        /// User
        /// </summary>
        class User
        {
            /// <summary>
            /// name
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// age
            /// </summary>
            public int age { get; set; }
        }

        /// <summary>
        /// 
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            InitUI();
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitUI()
        {
            dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            //繫結資料
            dgv.DataSource = new List<User>
            {
                new User { name = "abc", age = 18 },
                new User { name = "ewe", age = 20 }
            };

            //繫結完成後修改欄位標題
            dgv.DataBindingComplete += (s, e) =>
            {
                dgv.Columns["name"].HeaderText = "姓名";
                dgv.Columns["age"].HeaderText = "年齡";
            };
            this.Controls.Add(dgv);
        }

    }
}


沒有留言:

張貼留言