给 winform datagridview 头部 添加 checkbox 全选控件

时间:2022-11-17 19:38:43
我是参考了这里的代码后修改的,把放checkbox的列设置个宽度就能使用了,原版的在显示全选框样式上有很大问题,稍微修改下页面就比较和谐了
    /// <summary>  
/// 给DataGridView添加全选
/// reference:http://blog.csdn.net/netgyc/article/details/5578628,
/// </summary>
public class AddCheckBoxToDataGridView
{
public static System.Windows.Forms.DataGridView dgv;
public static void AddFullSelect()
{
System.Windows.Forms.CheckBox ckBox = new System.Windows.Forms.CheckBox();
ckBox.Text = "";
ckBox.Checked = false;
System.Drawing.Rectangle rect = dgv.GetCellDisplayRectangle(0, -1, true);
ckBox.Size = new System.Drawing.Size(13, 13);
ckBox.Location = new Point(rect.Location.X + dgv.Columns[0].Width / 2 - 13 / 2 - 1, rect.Location.Y + 3);
//ckBox.Location.Offset(-40, rect.Location.Y);
ckBox.CheckedChanged += new EventHandler(ckBox_CheckedChanged);
dgv.Controls.Add(ckBox);
}
static void ckBox_CheckedChanged(object sender, EventArgs e)
{
for (int i = 0; i < dgv.Rows.Count; i++)
{
dgv.Rows[i].Cells["chk"].Value = ((System.Windows.Forms.CheckBox)sender).Checked;
}
dgv.EndEdit();
}
}
然后在页面 _Load事件中加入代码即可
            AddCheckBoxToDataGridView.dgv = 你的datagridview的id;
AddCheckBoxToDataGridView.AddFullSelect();