Click here to Skip to main content
11,414,561 members (68,311 online)
Click here to Skip to main content

CheckBox Header Column For DataGridView

, 24 Aug 2007
Rate this:
Please Sign up or sign in to vote.
Presenting a solution for having CheckBox control in the header of DataGridView

Introduction

This article will show you how to create CheckBoxHeaderColumn for DataGridView. It will expose CheckBoxClicked event which you can consume in your client application.

Background

It is very common to have a list of items in DataGridView with a check box in the first column where your later action will depend on user selection. This can be very easily done by having a first column defined as DataGridViewCheckBoxCell object. But, how can your customer select all items in the list (let's say you are working on an email client app and the user wants to delete all of his 100 spams). This was the main idea to generate a class which will have a check box item in the header where the developer can have full control after the user checks/unchecks an item in the header. A common action is to check/uncheck all items in the DataGridView depending on whether the header is checked/unchecked.

Using the Code

The whole solution (control) is very simple and contains just one class DataGridViewCheckBoxHeaderCell.

On the client side, the developer just needs to define DataGridViewCheckBoxColumn and assign DataGridCheckBoxHeaderCell as a HeaderCell. Here is the code to do that:

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

As mentioned before, always user clicks on a Checkbox in the header object will fire CheckboxClicked event which you can consume in your application:

cbHeader.OnCheckBoxClicked += 
    new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);

In the function cbHeader_OnCheckBoxClicked(), you can check/uncheck all of DataGridView rows or do any other action.

And here is a control source:

namespace TestRef
{   
    public delegate void CheckBoxClickedHandler(bool state);
    public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
    {
        bool _bChecked;
        public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked)
        {
            _bChecked = bChecked;
        }
        public bool Checked
        {
            get { return _bChecked; }
        }
    }
    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);
        }     
    }
}

I hope you will find this article helpful while this is a solution used in our cross database comparison tool for selecting rows for synchronization between databases. Besides this, you can easily extend and fully customize painting of the CheckBox control, introduce tri state CheckBoxes and do many others as with the normal CheckBox.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

DLM@TD
Software Developer (Senior)
Austria Austria
Working as a .NET and database developer

Comments and Discussions

 
QuestionUse Pin
aramosvizcarra28-Aug-14 4:26
memberaramosvizcarra28-Aug-14 4:26 
AnswerRe: Use Pin
DLM@TD25-Sep-14 9:14
memberDLM@TD25-Sep-14 9:14 
SuggestionVersion based on CheckBoxState: unchecked, checked, mixed and normal, hot, pressed Pin
dethtroll27-Jan-12 6:16
memberdethtroll27-Jan-12 6:16 
Questiona vb.net version Pin
jtxd30-Dec-11 16:32
memberjtxd30-Dec-11 16:32 
AnswerRe: a vb.net version Pin
Brent Murphy11-Jan-12 4:27
memberBrent Murphy11-Jan-12 4:27 
GeneralRe: a vb.net version Pin
tallion18-Nov-12 14:33
membertallion18-Nov-12 14:33 
QuestionSetting 'DataPropertyName' stopped the OnCheckBoxClicked event firing Pin
trevormcalister17-Aug-11 5:31
membertrevormcalister17-Aug-11 5:31 
AnswerRe: Setting 'DataPropertyName' stopped the OnCheckBoxClicked event firing Pin
mohammad forutan31-Jul-12 22:15
membermohammad forutan31-Jul-12 22:15 
GeneralThanks Pin
YZK30-Mar-11 1:03
groupYZK30-Mar-11 1:03 
GeneralMy vote of 5 Pin
JunfengGuo9-Mar-11 13:26
memberJunfengGuo9-Mar-11 13:26 
AnswerEven much simpler and a way to remove checkbox in an individual cell of in an CheckboxColumn Pin
loibl24-Mar-09 6:53
memberloibl24-Mar-09 6:53 
GeneralRe: Even much simpler and a way to remove checkbox in an individual cell of in an CheckboxColumn Pin
Christian Snook5-Nov-14 6:02
memberChristian Snook5-Nov-14 6:02 
QuestionHow to uncheck the header check box when user click on the grid cell and uncheck any of the check box Pin
ravikrmishra10-Feb-09 23:20
memberravikrmishra10-Feb-09 23:20 
AnswerRe: Solution: to uncheck the header check box when user click on the grid cell and uncheck any of the check box Pin
Viji Raj1-Jul-09 11:30
memberViji Raj1-Jul-09 11:30 
GeneralRe: Solution: to uncheck the header check box when user click on the grid cell and uncheck any of the check box Pin
Marpri22-Mar-12 1:55
memberMarpri22-Mar-12 1:55 
GeneralAppend check box after a column label Pin
TuttiFiesta30-Jan-09 4:48
memberTuttiFiesta30-Jan-09 4:48 
GeneralRe: Append check box after a column label Pin
TuttiFiesta30-Jan-09 5:23
memberTuttiFiesta30-Jan-09 5:23 
GeneralOne more thing needed.... Pin
Janette M Layton1-May-08 14:49
memberJanette M Layton1-May-08 14:49 
GeneralEvent not registered Pin
Aschmutt8-Feb-08 6:42
memberAschmutt8-Feb-08 6:42 
GeneralRe: Event not registered Pin
Aschmutt11-Feb-08 3:15
memberAschmutt11-Feb-08 3:15 
QuestionCurrent Cell/Row not updating Pin
pyerwoh18-Oct-07 12:16
memberpyerwoh18-Oct-07 12:16 
AnswerRe: Current Cell/Row not updating Pin
DLM@bypsoft19-Oct-07 15:21
memberDLM@bypsoft19-Oct-07 15:21 
AnswerRe: Current Cell/Row not updating Pin
jtxd30-Dec-11 16:23
memberjtxd30-Dec-11 16:23 
GeneralError Pin
nzakir24-Sep-07 18:16
membernzakir24-Sep-07 18:16 
QuestionRe: Error Pin
nzakir24-Sep-07 18:34
membernzakir24-Sep-07 18:34 
GeneralComboBox in Header Pin
ctuzzolino18-Sep-07 9:04
memberctuzzolino18-Sep-07 9:04 
GeneralRe: ComboBox in Header Pin
DLM@bypsoft18-Sep-07 10:22
memberDLM@bypsoft18-Sep-07 10:22 
GeneralRe: ComboBox in Header Pin
ctuzzolino18-Sep-07 10:25
memberctuzzolino18-Sep-07 10:25 
AnswerRe: ComboBox in Header Pin
DLM@bypsoft19-Sep-07 3:37
memberDLM@bypsoft19-Sep-07 3:37 
GeneralRe: ComboBox in Header Pin
ctuzzolino27-Sep-07 3:34
memberctuzzolino27-Sep-07 3:34 
Generala little help Pin
pras0109198117-Sep-07 4:51
memberpras0109198117-Sep-07 4:51 
GeneralEnhanced Class Pin
Laurent Muller28-Aug-07 3:11
memberLaurent Muller28-Aug-07 3:11 
GeneralRe: Enhanced Class Pin
DLM@bypsoft28-Aug-07 3:38
memberDLM@bypsoft28-Aug-07 3:38 
GeneralRe: Enhanced Class Pin
Laurent Muller28-Aug-07 4:06
memberLaurent Muller28-Aug-07 4:06 
GeneralRe: Enhanced Class Pin
ScubaSteve2000116-Nov-07 6:08
memberScubaSteve2000116-Nov-07 6:08 
AnswerRe: Enhanced Class Pin
MicheleLaPietra26-Jun-08 0:19
memberMicheleLaPietra26-Jun-08 0:19 
GeneralRe: Enhanced Class Pin
William F26-Jan-10 0:09
memberWilliam F26-Jan-10 0:09 
GeneralRe: Enhanced Class Pin
Pravin S. Kadam25-Feb-10 3:02
memberPravin S. Kadam25-Feb-10 3:02 
GeneralThanks! Pin
Chemically Yours24-Aug-07 4:17
memberChemically Yours24-Aug-07 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.4 | Last Updated 24 Aug 2007
Article Copyright 2007 by DLM@TD
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid