星期二, 7月 26, 2016

[C#] DataGridView - 計算欄位

在 VFP 中,只要直接在 Grid ControlSource 內填入計算式,就可以產生計算欄位資料,C# DataGridView 則是要 VirtualMode 搭配 CellValueNeed Event 來作到

Project
[C#] DataGridView - 計算欄位-1

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

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

            dataGridView1.Columns.Add(
                new DataGridViewTextBoxColumn {
                    DataPropertyName = "N1",
                    Name = "Col1",
                    HeaderText = "數字欄位 1",
                    Width = 100,
                    Visible = true });

            dataGridView1.Columns.Add(
                new DataGridViewTextBoxColumn {
                    DataPropertyName = "N2",
                    Name = "Col2",
                    HeaderText = "數字欄位 2",
                    Width = 100,
                    Visible = true });

            // 計算欄位設為 ReadOnly 比較符合實務情況
            dataGridView1.Columns.Add(
                new DataGridViewTextBoxColumn {
                    DataPropertyName = "",
                    Name = "Col3",
                    HeaderText = "計算欄位",
                    Width = 100,
                    Visible = true,
                    ReadOnly = true });

            dataGridView1.VirtualMode = true;
            dataGridView1.CellValueNeeded += DataGridView1_CellValueNeeded;
        }

        private void DataGridView1_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
        {
            if (e.RowIndex < 0) return;

            DataGridView DGV = sender as DataGridView;
            if (e.ColumnIndex != DGV.Columns["Col3"].Index) return;

            // 方法一:利用 DataGridView 取值
            e.Value = (int)DGV.Rows[e.RowIndex].Cells["Col1"].Value + (int)DGV.Rows[e.RowIndex].Cells["Col2"].Value;

            // 方法二:利用 DataTable 取值
            DataTable dt = DGV.DataSource as DataTable;
            e.Value = (int)(dt.DefaultView[e.RowIndex]["N1"]) + (int)(dt.DefaultView[e.RowIndex]["N2"]);
        }

        private DataTable GetDataSource()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("N1", typeof(int));
            dt.Columns.Add("N2", typeof(int));

            dt.Rows.Add(1, 1);
            dt.Rows.Add(2, 2);
            dt.Rows.Add(3, 3);
            dt.Rows.Add(4, 4);
            dt.Rows.Add(5, 5);

            return dt;
        }
    }
}
結果
[C#] DataGridView - 計算欄位-2

沒有留言:

張貼留言