DataGridView custom column header content (checkbox control)

杀马特。学长 韩版系。学妹 提交于 2019-12-08 09:50:28

问题


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

It should look like the following:

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?


回答1:


Try this: http://tech.chitgoks.com/2008/11/17/c-add-select-all-deselect-all-checkbox-in-column-header-in-datagridview-control/




回答2:


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;
}


来源:https://stackoverflow.com/questions/12642348/datagridview-custom-column-header-content-checkbox-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!