0

是否可以将“检查所有”功能添加到 WinForms DataGridViewDataGridViewCheckBoxColumn

它应该如下所示:

在此处输入图像描述

单击突出显示的复选框应选中/取消选中网格中的所有复选框。

如我所见,列标题只能包含字符串值。有什么解决方法吗?

4

2 回答 2

0

最终实现主要是解决方案,由 Samir 在本文中提出。

但是当网格水平滚动条移动时,它需要修复复选框位置。因此,以下是需要更改的方法:

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;
}
于 2012-09-28T15:53:49.507 回答