GridHeader CheckBox

By | 2014년 8월 30일

CheckBox

private void HeaderCheckBox_MouseClick(object sender, MouseEventArgs e)
{
    HeaderCheckBoxClick((CheckBox)sender);
}

private void HeaderCheckBox_KeyUp(object sender, KeyEventArgs e)
{
    if(e.KeyCode == Keys.Space)
        HeaderCheckBoxClick((CheckBox)sender);
}

private void dgvSelectAll_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex == -1 && e.ColumnIndex == 0)
       ResetHeaderCheckBoxLocation(e.ColumnIndex, e.RowIndex);
}

private void AddHeaderCheckBox()
{
    HeaderCheckBox = new CheckBox();

    HeaderCheckBox.Size = new Size(15, 15);

    //Add the CheckBox into the DataGridView
    this.dgvSelectAll.Controls.Add(HeaderCheckBox);
}

private void ResetHeaderCheckBoxLocation(int ColumnIndex, int RowIndex)
{
    //Get the column header cell bounds
    Rectangle oRectangle = this.dgvSelectAll.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);

    Point oPoint = new Point();

    oPoint.X = oRectangle.Location.X + (oRectangle.Width - HeaderCheckBox.Width) / 2 + 1;
    oPoint.Y = oRectangle.Location.Y + (oRectangle.Height - HeaderCheckBox.Height) / 2 + 1;

    //Change the location of the CheckBox to make it stay on the header
    HeaderCheckBox.Location = oPoint;
}

private void HeaderCheckBoxClick(CheckBox HCheckBox)
{
    IsHeaderCheckBoxClicked = true;

    foreach (DataGridViewRow Row in dgvSelectAll.Rows)
        ((DataGridViewCheckBoxCell)Row.Cells["chkBxSelect"]).Value = HCheckBox.Checked;

    dgvSelectAll.RefreshEdit();

    TotalCheckedCheckBoxes = HCheckBox.Checked ? TotalCheckBoxes : 0;

    IsHeaderCheckBoxClicked = false;
}

private void RowCheckBoxClick(DataGridViewCheckBoxCell RCheckBox)
{
    if (RCheckBox != null)
    {
        //Modifiy Counter;            
        if ((bool)RCheckBox.Value && TotalCheckedCheckBoxes < TotalCheckBoxes)
            TotalCheckedCheckBoxes++;
        else if (TotalCheckedCheckBoxes > 0)
            TotalCheckedCheckBoxes--;

        //Change state of the header CheckBox.
        if (TotalCheckedCheckBoxes < TotalCheckBoxes)
            HeaderCheckBox.Checked = false;
        else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
            HeaderCheckBox.Checked = true;
    }
}

Category: C#