[DataGridView] CheckBox Select All of the Datagridview

[DataGridView] CheckBox Select All of the Datagridview

image

.Designer.cs


{
    partial class Form1
    {
        /// <summary>
        /// 設計工具所需的變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清除任何使用中的資源。
        /// </summary>
        /// <param name="disposing">如果應該處置 Managed 資源則為 true,否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 設計工具產生的程式碼

        /// <summary>
        /// 此為設計工具支援所需的方法 - 請勿使用程式碼編輯器修改這個方法的內容。
        ///
        /// </summary>
        private void InitializeComponent()
        {
            this.dgv = new System.Windows.Forms.DataGridView();
            this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            this.Column3 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            ((System.ComponentModel.ISupportInitialize)(this.dgv)).BeginInit();
            this.SuspendLayout();
            // 
            // dgv
            // 
            this.dgv.AllowUserToAddRows = false;
            this.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2,
            this.Column3});
            this.dgv.Location = new System.Drawing.Point(12, 12);
            this.dgv.Name = "dgv";
            this.dgv.RowTemplate.Height = 24;
            this.dgv.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
            this.dgv.Size = new System.Drawing.Size(363, 207);
            this.dgv.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(dgv_CellContentClick);
            this.dgv.TabIndex = 0;
            // 
            // Column1
            // 
            this.Column1.HeaderText = "Column1";
            this.Column1.Name = "Column1";
            // 
            // Column2
            // 
            this.Column2.HeaderText = "Column2";
            this.Column2.Name = "Column2";
            // 
            // Column3
            // 
            this.Column3.HeaderText = "Column3";
            this.Column3.Name = "Column3";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(387, 231);
            this.Controls.Add(this.dgv);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dgv)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView dgv;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        private System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
        private System.Windows.Forms.DataGridViewCheckBoxColumn Column3;
    }
}

.cs


using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CheckBoxSelectAllOfTheDatagridview
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            object[][] dbData = new object[][]
            {new object[]{1,null,null}
            ,new object[]{2,null,null}
            ,new object[]{3,null,null}
            ,new object[]{4,null,null}
            ,new object[]{5,null,null}};

            foreach (object[] obj in dbData)
                dgv.Rows.Add(obj);

            //第一組 CheckBoxHeaderCell
            CheckBoxSelectAll.DatagridViewCheckBoxHeaderCell cbHeader1 = new CheckBoxSelectAll.DatagridViewCheckBoxHeaderCell();
            Column2.HeaderCell = cbHeader1;
            Column2.HeaderText = "Column2";
            cbHeader1.OnCheckBoxClicked += new CheckBoxSelectAll.CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);

            //第二組 CheckBoxHeaderCell
            CheckBoxSelectAll.DatagridViewCheckBoxHeaderCell cbHeader2 = new CheckBoxSelectAll.DatagridViewCheckBoxHeaderCell();
            Column3.HeaderCell = cbHeader2;
            Column3.HeaderText = "Column3";
            cbHeader2.OnCheckBoxClicked += new CheckBoxSelectAll.CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);
        }

        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn)
            {
                if (((bool)dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) == true)
                {
                    ((CheckBoxSelectAll.DatagridViewCheckBoxHeaderCell)dgv.Columns[e.ColumnIndex].HeaderCell)._checked = false;

                    //為了 Reflash UI, 因此將該 Column 先隱藏再顯示
                    dgv.Columns[e.ColumnIndex].Visible = false;
                    dgv.Columns[e.ColumnIndex].Visible = true;
                }
            }
        }

        //DataGridView全選功能
        public void cbHeader_OnCheckBoxClicked(bool b, DataGridViewCellMouseEventArgs e)
        {
            bool value = false;

            if (b)
                value = b;

            foreach (DataGridViewRow row in dgv.Rows)
                row.Cells[e.ColumnIndex].Value = value;

            //因目前 Focus Row 上的 UI 未 Reflssh, 將會導致畫面勾選無反應, 因此自動將 Focus Row 設定為第一列
            if (this.dgv.RowCount > 0)
                this.dgv.CurrentCell = this.dgv[0, 0];
        }

        ////DataGridView全選按鈕
        public class CheckBoxSelectAll
        {
            public delegate void CheckBoxClickedHandler(bool state, DataGridViewCellMouseEventArgs e);//修改部分
            public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
            {
                bool _bChecked;
                int _column_X = 0;//增加部分
                public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked, DataGridViewCellMouseEventArgs ee)
                {
                    _bChecked = bChecked;
                    _column_X = ee.ColumnIndex;//增加部分
                }
                public bool Checked
                {
                    get { return _bChecked; }
                }
                public int column_X//增加部分
                {
                    get { return _column_X; }
                }
            }
            public class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
            {
                Point checkBoxLocation;
                Size checkBoxSize;
                public bool _checked = false;//更改全選checkbox狀態變數
                Point _cellLocation = new Point();
                System.Windows.Forms.VisualStyles.CheckBoxState _cbState =
                    System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;
                public event CheckBoxClickedHandler OnCheckBoxClicked;

                public DatagridViewCheckBoxHeaderCell() { }

                protected override void Paint(System.Drawing.Graphics graphics,
                    System.Drawing.Rectangle clipBounds,
                    System.Drawing.Rectangle cellBounds,
                    int rowIndex,
                    DataGridViewElementStates dataGridViewElementState,
                    object value,
                    object formattedValue,
                    string errorText,
                    DataGridViewCellStyle cellStyle,
                    DataGridViewAdvancedBorderStyle advancedBorderStyle,
                    DataGridViewPaintParts paintParts)
                {
                    base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                        dataGridViewElementState, value,
                        formattedValue, errorText, cellStyle,
                        advancedBorderStyle, paintParts);
                    Point p = new Point();
                    Size s = CheckBoxRenderer.GetGlyphSize(graphics,
                    System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
                    p.X = cellBounds.Location.X +
                        (cellBounds.Width) - (s.Width);
                    p.Y = cellBounds.Location.Y +
                        (cellBounds.Height) - (s.Height);
                    _cellLocation = cellBounds.Location;
                    checkBoxLocation = p;
                    checkBoxSize = s;
                    if (_checked)
                        _cbState = System.Windows.Forms.VisualStyles.
                            CheckBoxState.CheckedNormal;
                    else
                        _cbState = System.Windows.Forms.VisualStyles.
                            CheckBoxState.UncheckedNormal;
                    CheckBoxRenderer.DrawCheckBox
                    (graphics, checkBoxLocation, _cbState);


                }

                protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
                {
                    Point p = new Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
                    if (p.X >= checkBoxLocation.X && p.X <=
                        checkBoxLocation.X + checkBoxSize.Width
                    && p.Y >= checkBoxLocation.Y && p.Y <=
                        checkBoxLocation.Y + checkBoxSize.Height)
                    {
                        _checked = !_checked;
                        if (OnCheckBoxClicked != null)
                        {
                            OnCheckBoxClicked(_checked, e); //修改部分
                            this.DataGridView.InvalidateCell(this);
                        }

                    }
                    base.OnMouseClick(e);
                }
            }
        }
    }
}