是否可以向WinForms DataGridView 的 DataGridViewCheckBoxColumn 添加“全部检查”功能?
它应如下所示:
单击highlited复选框应选中/取消选中网格中的所有复选框。
正如我所看到的,列标题只能包含字符串值。有没有解决方法?
答案 0 :(得分:1)
答案 1 :(得分:0)
最终实施主要是解决方案,由Samir在this文章中提出。
但是当网格水平滚动条移动时,它需要修复复选框位置。所以下面是需要改变的方法:
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;
}