带CheckBox列头的DataGridView

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

        private void Form1_Load(object sender, EventArgs e)
        {
          
        }


        #region CheckBoxClass
        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            DataColumn column;
            //设置列
            for (int i = 0; i < 4; i++)
            {
                if (i == 0)//设置Checkbox
                {
                    column = new DataColumn();
                    column.ColumnName = "column" + i;
                    column.DataType = typeof(Boolean);
                    dt.Columns.Add(column);
                    dgvdata.DataSource = dt;
                }
                else
                {
                    column = new DataColumn();
                    column.ColumnName = "column" + i;
                    column.DataType = typeof(string);
                    dt.Columns.Add(column);
                }
            }
            //添加行数据
            for (int i = 0; i < 4; i++)
            {
                DataRow row = dt.NewRow();

                for (int j = 0; j < 4; j++)
                {

                    if (j ==0)
                    {
                        row[j] = true ;
                    }
                    else
                    {
                        row[j] = i.ToString();
                    }
                }
                dt.Rows.Add(row);
            }

            //dgvdata.DataSource = dt;
            dgvdata.DataSource = DBHelper.GET_MaterialOderList().Tables[0];//要将存储过程第一列设为bit类型与checkbox对应

          datagridviewCheckboxHeaderCell ch = new datagridviewCheckboxHeaderCell();
            ch.OnCheckBoxClicked += new datagridviewcheckboxHeaderEventHander(ch_OnCheckBoxClicked);

            //第1列为DataGridViewCheckBoxColumn
            DataGridViewCheckBoxColumn checkboxCol = this.dgvdata.Columns[0] as DataGridViewCheckBoxColumn;
            checkboxCol.HeaderCell = ch;
            checkboxCol.HeaderCell.Value = string.Empty;//消除列头checkbox旁出现的文字
            //设置除第一列外所有列为只读
            for (int i = 1; i < dgvdata.Columns.Count;i++ )
            {
                dgvdata.Columns[i].ReadOnly = true;
            }
        }

        void ch_OnCheckBoxClicked(object sender, Form1.datagridviewCheckboxHeaderEventArgs e)//为checkbox附值
        {
            foreach (DataGridViewRow dgvRow in this.dgvdata.Rows)
            {
                if (e.CheckedState)
                {
                    dgvRow.Cells[0].Value = true;
                }
                else
                {
                    dgvRow.Cells[0].Value = false;
                }
            }

        }

        //定义触发单击事件的委托
        private  delegate void datagridviewcheckboxHeaderEventHander(object sender, datagridviewCheckboxHeaderEventArgs e);


        //定义包含列头checkbox选择状态的参数类
         class datagridviewCheckboxHeaderEventArgs : EventArgs
        {
            private bool checkedState = true ;//默认为选中

            public bool CheckedState
            {
                get { return checkedState; }
                set { checkedState = value; }
            }
        }

        //定义继承于DataGridViewColumnHeaderCell的类,用于绘制checkbox,定义checkbox鼠标单击事件
        class datagridviewCheckboxHeaderCell : DataGridViewColumnHeaderCell
        {
            Point checkBoxLocation;
            Size checkBoxSize;
            bool _checked = true ;//默认选中
            Point _cellLocation = new Point();
            System.Windows.Forms.VisualStyles.CheckBoxState _cbState =
                System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;
            public event datagridviewcheckboxHeaderEventHander OnCheckBoxClicked;


            //绘制列头checkbox
            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 / 2) - (s.Width / 2) - 1;//列头checkbox的X坐标
                p.Y = cellBounds.Location.Y +
                    (cellBounds.Height / 2) - (s.Height / 2);//列头checkbox的Y坐标
                _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);
            }

            /// <summary>
            /// 点击列头checkbox单击事件
            /// </summary>
            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;

                    //获取列头checkbox的选择状态
                    datagridviewCheckboxHeaderEventArgs ex = new datagridviewCheckboxHeaderEventArgs();
                    ex.CheckedState = _checked;

                    object sender = new object();//此处不代表选择的列头checkbox,只是作为参数传递。应该列头checkbox是绘制出来的,无法获得它的实例

                    if (OnCheckBoxClicked != null)
                    {
                        OnCheckBoxClicked(sender, ex);//触发单击事件
                        this.DataGridView.InvalidateCell(this);
                    }
                }
                base.OnMouseClick(e);
            }
        }
    }//end class

 

        #endregion
      

 

=========================================================

在项目的开发中,在DataGridView中将CheckBox作为第一列使用的很平常,使用微软自带DataGridView中的DataGridViewCheckBoxCell,但是微软自带的DataGridView中又没有能够将CheckBox作为列头来做全选和全取消选择的功能。所以如果想实现在列头上显示一个CheckBox并且点击CheckBox来实现全选和全取消,就没有现成的。但是办法是人想出来的,既然微软没有能够提供现成的实现方法,那我们就要自己动手,才能丰衣足食了。其实这个功能实现起来也不是很难,我们首先要定义一个DatagridViewCheckBoxHeaderCell类,它是继承自DataGridViewColumnHeaderCell,主要是要重写里面的OnPaint方法和OnMouseClick方法即可,代码如下:

 class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
    {
        Point checkBoxLocation;
        Size checkBoxSize;
        bool _checked = false;
        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 / 2) - (s.Width / 2);
            p.Y = cellBounds.Location.Y +
                (cellBounds.Height / 2) - (s.Height / 2);
            _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);
                    this.DataGridView.InvalidateCell(this);
                }

            }
            base.OnMouseClick(e);
        }    

    }

 

除此之外,还需要加上事件处理的委托,代码如下:

 public delegate void CheckBoxClickedHandler(bool state);
    public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
    {
        bool _bChecked;
        public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked)
        {
            _bChecked = bChecked;
        }
        public bool Checked
        {
            get { return _bChecked; }
        }
    }

然后在客户端加上如下代码:

DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();DatagridViewCheckBoxHeaderCell cbHeader =new DatagridViewCheckBoxHeaderCell();colCB.HeaderCell = cbHeader;datagridview1.Columns.Add(colCB);

再在客户端完成事件处理:

cbHeader.OnCheckBoxClicked +=     new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);

主要的代码实现就这么多呢。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值