在DataGridView中实现Checkbox的全选的方法就是在列头画一个checkbox, 并给其一个事件.

这个之前很多blog都有写, 这里就不多废话了,  codeproject上面有示例代码.

这里我们再多做一层的封装,将其封装成一个控件,这样的话, 我们就可以最大程度上的复用, 而不需要老是重复写同样的, 无聊的代码了!

思路如下:

继承DataGridViewCheckBoxColumn类, 更改它的headerCell的样式. 添加cellValueChanged时间,使在进行复选框选择的时候可以触发事件,从而进行处理.

继承DataGridViewColumnHeaderCell类, 重新绘制一个带CheckBox的HeaderCell

话不多说直接上代码了, 如果有不懂的欢迎留言:

public class DataGridViewCheckBoxColumnSelectAll : DataGridViewCheckBoxColumn
{
private DatagridViewCheckBoxHeaderCell headerCell;
private bool loaded; public event CheckBoxClickedHandler OnCheckBoxClicked;
int TotalCheckedCheckBoxes = ;
bool IsHeaderCheckBoxClicked = false; public DataGridViewCheckBoxColumnSelectAll()
{
this.headerCell = new DatagridViewCheckBoxHeaderCell();
base.HeaderCell = this.headerCell; this.headerCell.OnCheckBoxClicked += new CheckBoxClickedHandler(this.headerCell_OnCheckBoxClicked);
this.loaded = false; } public DataGridViewCheckBoxColumnSelectAll(bool threeState)
: base(threeState)
{
this.headerCell = new DatagridViewCheckBoxHeaderCell();
base.HeaderCell = this.headerCell;
} /// <summary>
/// 在DataGridView改变时进行事件的绑定
/// </summary>
protected override void OnDataGridViewChanged()
{
if (this.DataGridView!=null)
{
this.DataGridView.CellValueChanged -= DataGridView_CellValueChanged;
this.DataGridView.CellValueChanged += DataGridView_CellValueChanged;
this.DataGridView.CurrentCellDirtyStateChanged -= DataGridView_CurrentCellDirtyStateChanged;
this.DataGridView.CurrentCellDirtyStateChanged += DataGridView_CurrentCellDirtyStateChanged;
}
} /// <summary>
/// 在复选的时候进行判断.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex>=&&e.ColumnIndex>=)
{
if (!IsHeaderCheckBoxClicked)
RowCheckBoxClick((DataGridViewCheckBoxCell)this.DataGridView[e.ColumnIndex, e.RowIndex]);
} } /// <summary>
/// 在复选框被选中的时候触发该事件, 该事件用于触发ValueChanged事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.DataGridView.CurrentCell is DataGridViewCheckBoxCell)
this.DataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
} /// <summary>
/// 复选框被点击时所需要做的操作
/// </summary>
/// <param name="checkBox"></param>
private void RowCheckBoxClick(DataGridViewCheckBoxCell checkBox)
{
var head = this.headerCell as DatagridViewCheckBoxHeaderCell;
if (checkBox != null)
{
//计算所有被选中的行的数量
if ((bool)checkBox.Value && TotalCheckedCheckBoxes < this.DataGridView.RowCount)
TotalCheckedCheckBoxes++;
else if (TotalCheckedCheckBoxes > )
TotalCheckedCheckBoxes--; //当所有复选框都被选中的时候,列的头上的复选框被选中, 反之则不被选中.
if (TotalCheckedCheckBoxes < this.DataGridView.RowCount)
head.IsChecked = false;
else if (TotalCheckedCheckBoxes == this.DataGridView.RowCount)
head.IsChecked = true;
//强制repained
head.DataGridView.InvalidateCell(head);
}
} /// <summary>
/// 头被选中时触发OnCheckBoxClicked事件.
/// </summary>
/// <param name="state"></param>
private void headerCell_OnCheckBoxClicked(bool state)
{
if (this.OnCheckBoxClicked != null)
{
this.OnCheckBoxClicked(state);
}
} }
 public delegate void CheckBoxClickedHandler(bool state);

    internal class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
{
private CheckBoxState _cbState = CheckBoxState.UncheckedNormal;
private Point _cellLocation = new Point();
private bool _checked;
private Point checkBoxLocation;
private Size checkBoxSize; public bool IsChecked
{
get
{
return _checked;
} set
{
_checked = value;
if (this._checked)
{
this._cbState = CheckBoxState.CheckedNormal;
}
else
{
this._cbState = CheckBoxState.UncheckedNormal;
}
}
} public event CheckBoxClickedHandler OnCheckBoxClicked; /// <summary>
/// 点击列头的时候触发的事件,这里有个判断, 如果点击的位置是复选框则触发OnCheckBoxClicked事件.
/// </summary>
/// <param name="e"></param>
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
{
Point point = new Point(e.X + this._cellLocation.X, e.Y + this._cellLocation.Y);
if (((point.X >= this.checkBoxLocation.X) && (point.X <= (this.checkBoxLocation.X + this.checkBoxSize.Width))) && ((point.Y >= this.checkBoxLocation.Y) && (point.Y <= (this.checkBoxLocation.Y + this.checkBoxSize.Height))))
{
this._checked = !this._checked;
bool temp = this._checked;
if (this.OnCheckBoxClicked != null)
{
this.OnCheckBoxClicked(this._checked);
base.DataGridView.InvalidateCell(this);
}
foreach (DataGridViewRow row in base.DataGridView.Rows)
{
((DataGridViewCheckBoxCell)row.Cells[e.ColumnIndex]).Value = temp;
}
base.DataGridView.RefreshEdit(); }
base.OnMouseClick(e);
} /// <summary>
/// 绘制一个CheckBox
/// </summary>
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates dataGridViewElementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
Point point = new Point();
Size glyphSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal);
point.X = (cellBounds.Location.X + (cellBounds.Width / 2)) - (glyphSize.Width / 2);
point.Y = (cellBounds.Location.Y + (cellBounds.Height / 2)) - (glyphSize.Height / 2);
this._cellLocation = cellBounds.Location;
this.checkBoxLocation = point;
this.checkBoxSize = glyphSize;
if (this._checked)
{
this._cbState = CheckBoxState.CheckedNormal;
}
else
{
this._cbState = CheckBoxState.UncheckedNormal;
}
CheckBoxRenderer.DrawCheckBox(graphics, this.checkBoxLocation, this._cbState);
} }

  源码位置:

http://pan.baidu.com/s/1jGJzErs

DataGridView中实现checkbox全选的自定义控件的更多相关文章

  1. 关于Winform下DataGridView中实现checkbox全选反选、同步列表项的处理

    近期接手一个winform 项目,虽然之前有.net 的经验,但是对一些控件的用法还不是很熟悉. 这段时间将会记录一些在工作中遇到的坎坷以及对应的解决办法,写出来与大家分享并希望大神提出更好解决方法来 ...

  2. vue中的checkbox全选和反选

    前几天有个博客园的朋友问小颖,小颖之前写的vue2.0在table中实现全选和反选  .Vue.js实现checkbox的全选和反选,为什么他将里面的js复制下来,但是实现不了全选和反选.小颖当时看他 ...

  3. datagridview里面的checkbox全选和取消全选

    全选 设置全选button,选中所有的checkbox private void selectAll_Click(object sender, EventArgs e) { //遍历datagridv ...

  4. C# WinForm中实现CheckBox全选反选功能

    今天一群里有人问到这个功能,其实应该挺简单,但提问题的人问题的出发点并没有描述清楚.因此,一个简简单单的需求,就引起了群内热烈的讨论.下面看看这个功能如何去实现,先上效果: 下面直接上代码,请不要在意 ...

  5. DataGrid列中加入CheckBox 全选 点击Header全选 和 只操作选中部分 功能的实现

    先写个效果 中午接着写 反正没人看 只是给自己记录

  6. 利用jQuery实现CheckBox全选/全不选/反选

    转自:http://www.cnblogs.com/linjiqin/p/3148259.html jQuery有些版本中实现CheckBox全选/全不选/反选会有bug,经测试jquery-1.3. ...

  7. jquery中checkbox全选失效的解决方法

    这篇文章主要介绍了jquery中checkbox全选失效的解决方法,需要的朋友可以参考下     如果你使用jQuery 1.6 ,代码if ( $(elem).attr(“checked”) ),将 ...

  8. Datagridview 添加checkbox列,并判断Datagridview 中的checkbox列是否被选中

    Solution1://In Fill DataGridViewEvent : DataGridViewCheckBoxColumn ChCol = new DataGridViewCheckBoxC ...

  9. JS checkbox 全选 全不选

    /* JS checkbox 全选 全不选 Html中checkbox: <input type="checkbox" name="cbx" value= ...

随机推荐

  1. KVM 基本命令

    一.问题描述: KVM中宿主机通过console无法连接客户机,卡在这里不动了. # virsh console vm01 Connected to domain vm01 Escape charac ...

  2. UILabel笔记(待完善)

    UIlabel的换行由 numberOfLines 属性控制,当为0时,则会自动换到适合的行数: 换行的模式由 lineBreakMode 属性控制: public enum NSLineBreakM ...

  3. Unity运行时检测Altas使用情况

    UI贴图在游戏中内存大小中占的分量非常非常大,尤其对于前期对UI没有规划的项目,无论是包量还是内存大小都是需要花费很多时间去优化.如果涉及到战斗场景和逻辑场景的情况下,常用的做法就是把两个场景使用的a ...

  4. 几何服务,cut功能,输入要素target(修改前)内容。

    几何服务,cut功能测试,输入要素target(修改前)内容. {"geometryType":"esriGeometryPolyline","geo ...

  5. java基础总结——开篇

    工作三年多了,一直没时间静下心来好好总结,2016年马上就要过去了.也算是给自己在新一年的一个任务吧!总结java基础,然后再总结javaweb.纯属个人学习总结,总结过程中如有模糊的地方,望各位看官 ...

  6. 基于apache的tomcat负载均衡和集群配置

    最近不是很忙,用零碎时间做点小小的实验. 以前公司采用F5负载均衡交换机,F5将请求转发给多台服务器,每台服务器有多个webserver实例,每个webserver分布在多台服务器,交叉式的分布集群. ...

  7. js 获取滚动条的高度 以及 设置滚动条的高度

    //设置窗口滚动条高度 function setScrollTop(top){ if(!isNaN(top))document.body.scrollTop = top; } //取窗口滚动条高度 f ...

  8. objective-c static变量的使用总结

    在java中,我们经常使用的是单例模式,这些设计模式在ios开发中也比较常用,最近也在考虑使用在ios开发中使用单例模式 在objective-c中,需要在.m文件里面定义个static变量来表示全局 ...

  9. PL/SQL %TYPE和%ROWTYPE的区别【转】

    %TYPE: 定义一个变量,其数据类型与已经定义的某个 数据变量的类型相同,或者与数据库表的某个列的数据类型 相同,这时可以使用%TYPE.         使用%TYPE 特性的优点在于: 1.所引 ...

  10. Big Data

    Hadoop安装教程_伪分布式配置_CentOS6.4/Hadoop2.6.0 http://dblab.xmu.edu.cn/blog/install-hadoop-in-centos/ Spark ...