第一步:
private void BoxDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{if (e.RowIndex == -1 & e.ColumnIndex == 0)
{
Point p = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
p.Offset(2, 0);
SelectAll.Location = p;
SelectAll.Size = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Size;
SelectAll.Visible = true;
SelectAll.BringToFront();
}
}
在实现cellPainting在里面加入一个checkbox,这个是在列头加入
第二步:
private void SelectAll_CheckedChanged(object sender, EventArgs e)
{
EndEdit(DataGridViewDataErrorContexts.Commit);
for (int i = 0; i < RowCount; i++)
{
Rows.SharedRow(i).SetValues(SelectAll.Checked);
}
CommitEdit(DataGridViewDataErrorContexts.Commit);
}
实现在列头添加的checkbox的checkedchanged方法,在里面必须要注意for外边的两行代码,如果没有这两行代码会导致第一行是无法选中的,除非你先点击datagridview中的某行。
(注意)winform的datagridview列头是不带checkbox的,如果要就需要自己画上去。
第三步:
如果整个datagridview出现了水平的滚动条那么在滚动到comboboxcheckcolumn不显示的时候,刚刚画的combobox还是会显示出来的,所以在scroll事件里面做一下处理
private void BoxDataGridView_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
scrolling = true;
}
完整代码如下:
private CheckBox SelectAll = new CheckBox();
private bool scrolling = false;
public BoxDataGridView() : this(new List<CPackageInfo>())
{
SelectAll.BackColor = Color.Transparent;
SelectAll.Visible = false;
this.CellPainting += new DataGridViewCellPaintingEventHandler(BoxDataGridView_CellPainting);
this.Scroll += new ScrollEventHandler(BoxDataGridView_Scroll);
SelectAll.CheckedChanged += new EventHandler(SelectAll_CheckedChanged);
Controls.Add(SelectAll);
}
private void BoxDataGridView_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
scrolling = true;
}
private void SelectAll_CheckedChanged(object sender, EventArgs e)
{
EndEdit(DataGridViewDataErrorContexts.Commit);
for (int i = 0; i < RowCount; i++)
{
Rows.SharedRow(i).SetValues(SelectAll.Checked);
}
CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void BoxDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 & e.ColumnIndex == 0)
{
scrolling = false;
Point p = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
p.Offset(2, 0);
SelectAll.Location = p;
SelectAll.Size = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false).Size;
SelectAll.Visible = true;
SelectAll.BringToFront();
}
else
{
if (scrolling)
SelectAll.Visible = false;
}
}
本文介绍了如何在WinForm的DataGridView中实现行全选功能,包括在列头添加CheckBox,处理Checkbox的CheckedChanged事件以同步所有行的选中状态,并解决水平滚动时自定义Checkbox显示问题的代码实现。
1万+

被折叠的 条评论
为什么被折叠?



