Click here to Skip to main content
15,921,276 members
Articles / Programming Languages / C#
Article

Column Header CheckBox in DataGridView (Winfoms)

Rate me:
Please Sign up or sign in to vote.
3.61/5 (12 votes)
4 Jan 2008CPOL 170.5K   6   60   17
How to display Column Header CheckBox in Winfoms DataGridView

Introduction

This article will explains about creating & displaying Column Header CheckBox in winforms DataGridView.

Background

Bydefault DataGridView doen't supports column header chekbox, for this we need to write a class which is inherited by DataGridViewColumnHeaderCell class.

1) Add a boolean propery named CheckAll in that class to maintain the seleced state of Header checkbox.

2) override default implemention of Paint method. In this method, drawing the CheckBox at column Header.

3) override its OnMouseClick event. Here handle the click event of header checkbox.

I have created class named DGVColumnHeader as follows...

class DGVColumnHeader : DataGridViewColumnHeaderCell
{
    private Rectangle CheckBoxRegion;
    private bool checkAll = false;

    protected override void Paint(Graphics graphics,
        Rectangle clipBounds, 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);

        graphics.FillRectangle(new SolidBrush(cellStyle.BackColor), cellBounds);

        CheckBoxRegion = new Rectangle(
            cellBounds.Location.X + 1,
            cellBounds.Location.Y + 2,
            25, cellBounds.Size.Height - 4);


        if (this.checkAll)
            ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Checked);
        else
            ControlPaint.DrawCheckBox(graphics, CheckBoxRegion, ButtonState.Normal);

        Rectangle normalRegion =
            new Rectangle(
            cellBounds.Location.X + 1 + 25,
            cellBounds.Location.Y,
            cellBounds.Size.Width - 26,
            cellBounds.Size.Height);

        graphics.DrawString(value.ToString(), cellStyle.Font, new SolidBrush(cellStyle.ForeColor), normalRegion);
    }

    protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
    {
        //Convert the CheckBoxRegion
        Rectangle rec = new Rectangle(new Point(0, 0), this.CheckBoxRegion.Size);
        this.checkAll = !this.checkAll;
        if (rec.Contains(e.Location))
        {
            this.DataGridView.Invalidate();
        }
        base.OnMouseClick(e);
    }

    public bool CheckAll
    {
        get { return this.checkAll; }
        set { this.checkAll = value; }
    }
}
First Initialize a object of DGVColumnHeader add to DataGridView columns using Insert method at desired place. In this example i have added at first column and assigned to HeaderCell of it.

//Create the object of DGVColumnHeader
DGVColumnHeader dgvColumnHeader;
private void Form1_Load(object sender, EventArgs e)
{
    //initialize DGVColumnHeader object
    dgvColumnHeader = new DGVColumnHeader();

    //Add columns dynamically  to gridview
    dataGridView1.Columns.Insert(0, new DataGridViewCheckBoxColumn());
    dataGridView1.Columns[0].HeaderCell = dgvColumnHeader;

    //Data Binding
    DataTable dt = new DataTable();
    dt.Columns.Add("1");
    dt.Columns.Add("2");
    dt.Rows.Add("100", "101");
    dt.Rows.Add("102", "103");
    dataGridView1.DataSource = dt;
}
Add the following code in dataGridView1_ColumnHeaderMouseClick event to check/uncheck all the records based on the header checkbox state

private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            dataGridView1.Rows[i].Cells[0].Value = dgvColumnHeader.CheckAll;
        }
    }
}
When we select any of checkbox cell other than Header checkbox, by default grid will shows as edit mode. This we can handle using dataGridView1_CellClick event

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        for (int i = 0; i < this.dataGridView1.RowCount; i++)
        {
            //Escalate Editmode
            this.dataGridView1.EndEdit();
            string re_value = this.dataGridView1.Rows[i].Cells[0].EditedFormattedValue.ToString();
            this.dataGridView1.Rows[i].Cells[0].Value = "true";
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Singapore Singapore
C# Developer have Hands on Web Developement using ASP.NET, Web Services, Win Serivces, Pocket PC, Smart Device,Enterprize Security Applications and Win Forms Development using .NET FW 1.1 & 2.0.

Comments and Discussions

 
QuestionHow to disable and enable SortMode Pin
HansiWursti13-Sep-17 3:22
HansiWursti13-Sep-17 3:22 
GeneralGridview Pin
Member 1053975320-Dec-14 1:03
Member 1053975320-Dec-14 1:03 
QuestionThanks for your code. I used only Check box painting alone for better look Pin
red_annamalai22-May-14 3:07
red_annamalai22-May-14 3:07 
QuestionThanks Pin
alllaudhin24-Aug-13 5:33
alllaudhin24-Aug-13 5:33 
QuestionThanks Pin
alllaudhin24-Aug-13 5:32
alllaudhin24-Aug-13 5:32 
GeneralDataGridViewCheckbox column delete issue in Windows C# Pin
Palswipro17-Dec-09 3:38
Palswipro17-Dec-09 3:38 
GeneralRe: DataGridViewCheckbox column delete issue in Windows C# Pin
awadhendra tiwari22-Aug-11 2:46
awadhendra tiwari22-Aug-11 2:46 
GeneralThank you Pin
Karanig27-Sep-09 22:37
Karanig27-Sep-09 22:37 
GeneralSolution to uncheck the checkbox in the header when uncheck the checkbox in the rows. Pin
Viji Raj30-Jun-09 17:56
Viji Raj30-Jun-09 17:56 
GeneralRe: Solution to uncheck the checkbox in the header when uncheck the checkbox in the rows. Pin
krillgar7-Mar-12 3:40
krillgar7-Mar-12 3:40 
GeneralThanks Pin
mananthan7524-Mar-09 20:09
mananthan7524-Mar-09 20:09 
GeneralHow to uncheck the checkbox in the header. Pin
Member 149020928-Jun-09 19:05
Member 149020928-Jun-09 19:05 
Generalselect single checkBox Pin
kanza azhar6-Aug-08 9:05
kanza azhar6-Aug-08 9:05 
hiii,,

i just want to know how coult i capture the click or in other words select or deselect event of check box


i always use
datagridview1.rows[e.rowindex].cells[0].value.tostring();
but this does not work for checkBox
plz tell me the code to select a single checkbox


Regards.
GeneralRe: select single checkBox Pin
jackyonly200314-Jan-10 20:48
jackyonly200314-Jan-10 20:48 
QuestionHelp me. Checkbox in DataGridView Pin
thangnvhl13-May-08 21:21
thangnvhl13-May-08 21:21 
Generalhelp can you add also the original source Pin
sognant27-Jan-08 11:11
sognant27-Jan-08 11:11 
GeneralA little light in the "explain" department... Pin
Dave Kreskowiak4-Jan-08 10:36
mveDave Kreskowiak4-Jan-08 10:36 

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

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