实现效果
点击 CheckBox 或在第一列表头点击即可实现全选。
代码实现
假设你的 DataGridView 命名为 dgv,且已经默认添加了一个 DataGridViewCheckBoxColumn。勾选时值为 true,不勾选时为 false。
第一种:可视化拖动 CheckBox
直接在窗体上拖入一个 CheckBox 组件,然后绑定事件。
事件代码:
/// <summary>
/// checkbox1 的点击事件
/// </summary>
private void checkSelectAll_CheckedChanged(object sender, EventArgs e)
{
if (checkSelectAll.Checked)
{
foreach (DataGridViewRow dgvRow in this.dgv.Rows)
{
dgvRow.Cells["dataGridViewCheckBoxColumn1"].Value = true;
}
}
else
{
foreach (DataGridViewRow dgvRow in this.dgv.Rows)
{
dgvRow.Cells["dataGridViewCheckBoxColumn1"].Value = false;
}
}
}
第二种:自定义 HeaderCell
这种方式更灵活,需要自己弄一个继承自 DataGridViewColumnHeaderCell 的类来绘制 CheckBox。
核心类 DatagridviewCheckboxHeaderCell:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace MyApp
{
// 定义触发单击事件的委托
;
:
{
Point checkBoxLocation;
Size checkBoxSize;
_checked = ;
Point _cellLocation = Point();
CheckBoxState _cbState = CheckBoxState.UncheckedNormal;
DatagridviewcheckboxHeaderEventHander OnCheckBoxClicked;
{
.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, , formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
Size s = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal);
Point p = Point(cellBounds.Location.X + (cellBounds.Width / ) - (s.Width / ) - ,
cellBounds.Location.Y + (cellBounds.Height / ) - (s.Height / ));
_cellLocation = cellBounds.Location;
checkBoxLocation = p;
checkBoxSize = s;
_cbState = _checked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
CheckBoxRenderer.DrawCheckBox(graphics, checkBoxLocation, _cbState);
}
{
p = Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
(p.X >= checkBoxLocation.X && p.X <= checkBoxLocation.X + checkBoxSize.Width
&& p.Y >= checkBoxLocation.Y && p.Y <= checkBoxLocation.Y + checkBoxSize.Height)
{
_checked = !_checked;
DatagridviewCheckboxHeaderEventArgs ex = DatagridviewCheckboxHeaderEventArgs { CheckedState = _checked };
sender = ();
(OnCheckBoxClicked != )
{
OnCheckBoxClicked(sender, ex);
.DataGridView.InvalidateCell();
}
}
.OnMouseClick(e);
}
}
}


