Thursday, February 25, 2010

Header Cell with CheckBox in DataGridView

This is my version of a class that displays a check box in a DataGridView Header cell.
This is based on the code from http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/827907ea-c529-4254-9b15-2e6d571f5c5b

It assumes that the check box is located in the first DataGridView column. It allows for column caption and provides built-in check/uncheck functionality. Play with x and y parameters to place the checkbox where you want in the header cell.

Here is a usage example:

DataGridViewColumn column = new DataGridViewCheckBoxColumn();
CheckBox ckBoxMaster = CheckBoxInHeader.CreateCheckBoxInHeader(column, 12, 4, "     Select All");
DataGridView1.Controls.Add(ckBoxMaster);


The class listing:

  class CheckBoxInHeader
    {
    public static CheckBox CreateCheckBoxInHeader(DataGridViewColumn column, int x, int y, string caption)
    {
        CheckBoxInHeader cbInHeader = new CheckBoxInHeader();
        CheckBox ckBox = cbInHeader.CreateCheckBox(column, x, y, caption);
        ckBox.CheckedChanged += new EventHandler(cbInHeader.ckBox_CheckedChanged);
        return ckBox;
    }

    private CheckBox CreateCheckBox(DataGridViewColumn column, int x, int y, string caption)
    {
        CheckBox ckBox = new CheckBox();
        //Get the column header cell bounds          
        Rectangle rect = column.DataGridView.GetCellDisplayRectangle(0, -1, true);
        ckBox.Size = new Size(18, 18);
        //play with check box position
        rect.Offset(x, y);
        //Change the location of the CheckBox to make it stay on the header
        ckBox.Location = rect.Location;
        column.Name = caption;
        return ckBox;
    }

    private void ckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        DataGridView dgv = (DataGridView)cb.Parent;

        foreach (DataGridViewRow row in dgv.Rows)
        {

            row.Cells[0].Value = cb.Checked;
        }
    }

No comments:

Post a Comment