DataGridView自定义列标题内容(复选框控件) [英] DataGridView custom column header content (checkbox control)

查看:768
本文介绍了DataGridView自定义列标题内容(复选框控件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以向WinForms添加功能全部检查DataGridView 的DataGridViewCheckBoxColumn ?

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

它应该如下所示:

点击highlited复选框应该检查/取消选中网格中的所有复选框。

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?

推荐答案

最终实现主要是解决方案,由Samir在这篇文章。

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

这篇关于DataGridView自定义列标题内容(复选框控件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆