Sasha
Sasha

Reputation: 8850

DataGridView custom column header content (checkbox control)

Is it possible to add functionality "check all" to WinForms DataGridView's DataGridViewCheckBoxColumn?

It should look like the following:

enter image description here

Click on highlited checkbox should check/uncheck all checkboxes in the grid.

As I can see, column header can contain only string values. Is there any workaround?

Upvotes: 0

Views: 5330

Answers (2)

Sasha
Sasha

Reputation: 8850

Final implementation is mostly solution, proposed by Samir in this article.

But it requires fix of checkbox position when grid horizontal scrollbar is moving. So here follows methods that needed to be changed:

private void frmSelectAll_Load(object sender, EventArgs e)
{
    AddHeaderCheckBox();

    HeaderCheckBox.KeyUp += new KeyEventHandler(HeaderCheckBox_KeyUp);
    HeaderCheckBox.MouseClick += new MouseEventHandler(HeaderCheckBox_MouseClick);
    dgvSelectAll.CellValueChanged += new DataGridViewCellEventHandler(dgvSelectAll_CellValueChanged);
    dgvSelectAll.CurrentCellDirtyStateChanged += new EventHandler(dgvSelectAll_CurrentCellDirtyStateChanged);
    dgvSelectAll.CellPainting += new DataGridViewCellPaintingEventHandler(dgvSelectAll_CellPainting);

    BindGridView();

    var checkboxHeaderCellRect = dgvSelectAll.GetCellDisplayRectangle(0, -1, false);
    headerCheckboxRightMargin = (checkboxHeaderCellRect.Width - HeaderCheckBox.Width)/2;
}

private int headerCheckboxRightMargin;

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

    Point oPoint = new Point();

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

    if (oPoint.X < oRectangle.X)
    {
        HeaderCheckBox.Visible = false;
    }
    else
    {
        HeaderCheckBox.Visible = true;
    }

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

Upvotes: 0

Related Questions