datagridview 怎么在头一列加个全选?c#

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了datagridview 怎么在头一列加个全选?c#相关的知识,希望对你有一定的参考价值。

实现方式: 给DataGirdView动态添加CheckBox列
代码:
StringBuilder sql = new StringBuilder();
sql.Append("select * from aa");
DataSet ds = db.GetDataSet(sql.ToString());
if(ds==null)

dataGridView3.DataSource = "";
return;

//添加列
DataGridViewCheckBoxColumn newcol = new DataGridViewCheckBoxColumn();
newcol.HeaderText = "选择";
dataGridView3.Columns.Insert(0, newcol);
//添加完列再绑定数据源
dataGridView3.DataSource = ds.Tables[0];

触发checkbox的CheckedChanged事件
/// <summary>
/// 全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox1_CheckedChanged(object sender, EventArgs e)

if (checkBox1.Checked)
for (int i = 0; i < dataGridView3.Rows.Count; i++)
dataGridView3.Rows[i].Cells[0].Value = true;
else
for (int i = 0; i < dataGridView3.Rows.Count; i++)
dataGridView3.Rows[i].Cells[0].Value = false;


//添加其他类型的列(注意显示文字的设置)
第一: newedit.DefaultCellStyle.NullValue = "修改";
第二:newedit .UseColumnTextForButtonValue=true;
newedit .Text="修改";
示例:
dataGridView3.DataSource = ds.Tables[0];
DataGridViewButtonColumn newedit = new DataGridViewButtonColumn();
newedit.HeaderText = "编辑";
newedit.DefaultCellStyle.NullValue = "修改"; //列的显示文字
dataGridView3.Columns.Insert(9, newedit);//列的位置
参考技术A //允许datagridview一次选择多行,这个写load的事件里dgv.MultiSelect = true; 拖一个checkbox,将下面代码写在其CheckedChange事件中:if (ckbAll.Checked == true)

for (int i = 0; i < dgvMain.Rows.Count; i++)

for (int j = 0; j < dgvMain.Columns.Count; j++)

dgvMain[j, i].Selected = true;



else

dgvMain.ClearSelection();
参考技术B <asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate> <asp:CheckBox runat="server" ID="cbxall" Text="全选" /></HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="cbxsingle" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> 用模板列emplateField 如上 不用BoundField
参考技术C 恐怕这个功能不能直接完成,建议你到CSDN里看看一个重写DataGridView的完整示例代码:给你一个做好的内容:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataGridViewEx

public partial class Form1 : Form

public Form1()

InitializeComponent();


/// <summary>
/// 加载数据
/// </summary>
private void btnLoadData_Click(object sender, EventArgs e)

DataTable dtTemp = new DataTable();

using (SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=sa;database=testdb;"))

SqlDataAdapter sa = new SqlDataAdapter("select * from userinfo", con);
sa.Fill(dtTemp);


this.dataGridView1.DataSource = dtTemp;


/// <summary>
/// 在checkbox列显示列头checkbox
/// </summary>
/// <param name="sender"> </param>
/// <param name="e"> </param>
private void button1_Click(object sender, EventArgs e)


datagridviewCheckboxHeaderCell ch = new datagridviewCheckboxHeaderCell();
ch.OnCheckBoxClicked += new datagridviewcheckboxHeaderEventHander(ch_OnCheckBoxClicked);//关联单击事件

//第三列为DataGridViewCheckBoxColumn
DataGridViewCheckBoxColumn checkboxCol = this.dataGridView1.Columns[2] as DataGridViewCheckBoxColumn;
checkboxCol.HeaderCell = ch;
checkboxCol.HeaderCell.Value = string.Empty;//消除列头checkbox旁出现的文字


/// <summary>
/// 单击事件
/// </summary>
private void ch_OnCheckBoxClicked(object sender, datagridviewCheckboxHeaderEventArgs e)

foreach (DataGridViewRow dgvRow in this.dataGridView1.Rows)

if (e.CheckedState)

dgvRow.Cells[2].Value = true;

else

dgvRow.Cells[2].Value = false;





//定义触发单击事件的委托
public delegate void datagridviewcheckboxHeaderEventHander(object sender, datagridviewCheckboxHeaderEventArgs e);

//定义包含列头checkbox选择状态的参数类
class datagridviewCheckboxHeaderEventArgs : EventArgs

private bool checkedState = false;

public bool CheckedState

get return checkedState;
set checkedState = value;



//定义继承于DataGridViewColumnHeaderCell的类,用于绘制checkbox,定义checkbox鼠标单击事件
class datagridviewCheckboxHeaderCell : DataGridViewColumnHeaderCell

Point checkBoxLocation;
Size checkBoxSize;
bool _checked = false;
Point _cellLocation = new Point();
System.Windows.Forms.VisualStyles.CheckBoxState _cbState =
System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;
public event datagridviewcheckboxHeaderEventHander OnCheckBoxClicked;

//绘制列头checkbox
protected override void Paint(System.Drawing.Graphics graphics,
System.Drawing.Rectangle clipBounds,
System.Drawing.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 p = new Point();
Size s = CheckBoxRenderer.GetGlyphSize(graphics,
System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
p.X = cellBounds.Location.X +
(cellBounds.Width / 2) - (s.Width / 2) - 1;//列头checkbox的X坐标
p.Y = cellBounds.Location.Y +
(cellBounds.Height / 2) - (s.Height / 2);//列头checkbox的Y坐标
_cellLocation = cellBounds.Location;
checkBoxLocation = p;
checkBoxSize = s;
if (_checked)
_cbState = System.Windows.Forms.VisualStyles.
CheckBoxState.CheckedNormal;
else
_cbState = System.Windows.Forms.VisualStyles.
CheckBoxState.UncheckedNormal;
CheckBoxRenderer.DrawCheckBox
(graphics, checkBoxLocation, _cbState);


/// <summary>
/// 点击列头checkbox单击事件
/// </summary>
protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)


Point p = new Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
if (p.X >= checkBoxLocation.X && p.X <=
checkBoxLocation.X + checkBoxSize.Width
&& p.Y >= checkBoxLocation.Y && p.Y <=
checkBoxLocation.Y + checkBoxSize.Height)

_checked = !_checked;

//获取列头checkbox的选择状态
datagridviewCheckboxHeaderEventArgs ex = new datagridviewCheckboxHeaderEventArgs();
ex.CheckedState = _checked;

object sender = new object();//此处不代表选择的列头checkbox,只是作为参数传递。应该列头checkbox是绘制出来的,无法获得它的实例

if (OnCheckBoxClicked != null)

OnCheckBoxClicked(sender, ex);//触发单击事件
this.DataGridView.InvalidateCell(this);



base.OnMouseClick(e);




C#总结DataGridView增加全选列

  最近的一个winform的项目中,碰到datagridview控件的第一列添加全选的功能,通常这个功能,有两种实现方式:1. 为控件添加DataGridViewCheckBoxColumn来实现,但是需要提供全选反选功能,2. 再加一个checkbox控件跟datagridview组合来实现全选反选功能。但是,感觉这两种实现效果都不是很好。网上查资料,发现一个老外的实现方法,比较简单通用。demo 代码最下面的连接给出。

  他的实现方式就是:DataGridViewCheckBoxColumn的父类DataGridViewColumnHeaderCell 里面有个HeaderCell的属性,看下DataGridViewColumnHeaderCell 的继承关系,就可以知道它继承自DataGridViewCell类, 所以只需要重写DataGridViewColumnHeaderCell类的paint方法,用CheckBoxRenderer画一个Checkbox到单元格上。即可实现在datagridview的列头增加一个全选的checkbox 。以下是实现代码:

  

  实现代码

public delegate void CheckBoxClickedHandler(bool state);
    public class DataGridViewCheckBoxHeaderCellEventArgs : EventArgs
    {
        bool _bChecked;
        public DataGridViewCheckBoxHeaderCellEventArgs(bool bChecked)
        {
            _bChecked = bChecked;
        }
        public bool Checked
        {
            get { return _bChecked; }
        }
    }
    class DatagridViewCheckBoxHeaderCell : DataGridViewColumnHeaderCell
    {
        Point checkBoxLocation;
        Size checkBoxSize;
        bool _checked = false;
        Point _cellLocation = new Point();
        System.Windows.Forms.VisualStyles.CheckBoxState _cbState = 
            System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal;
        public event CheckBoxClickedHandler OnCheckBoxClicked;
 
        public DatagridViewCheckBoxHeaderCell()
        {           
        }

        protected override void Paint(System.Drawing.Graphics graphics, 
            System.Drawing.Rectangle clipBounds, 
            System.Drawing.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 p = new Point();
            Size s = CheckBoxRenderer.GetGlyphSize(graphics, 
            System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal);
            p.X = cellBounds.Location.X + 
                (cellBounds.Width / 2) - (s.Width / 2) ;
            p.Y = cellBounds.Location.Y + 
                (cellBounds.Height / 2) - (s.Height / 2);
            _cellLocation = cellBounds.Location;
            checkBoxLocation = p;
            checkBoxSize = s;
            if (_checked)
                _cbState = System.Windows.Forms.VisualStyles.
                    CheckBoxState.CheckedNormal;
            else
                _cbState = System.Windows.Forms.VisualStyles.
                    CheckBoxState.UncheckedNormal;
            CheckBoxRenderer.DrawCheckBox
            (graphics, checkBoxLocation, _cbState);
        }

        protected override void OnMouseClick(DataGridViewCellMouseEventArgs e)
        {
            Point p = new Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y);
            if (p.X >= checkBoxLocation.X && p.X <= 
                checkBoxLocation.X + checkBoxSize.Width 
            && p.Y >= checkBoxLocation.Y && p.Y <= 
                checkBoxLocation.Y + checkBoxSize.Height)
            {
                _checked = !_checked;
                if (OnCheckBoxClicked != null)
                {
                    OnCheckBoxClicked(_checked);
                    this.DataGridView.InvalidateCell(this);
                }
                
            } 
            base.OnMouseClick(e);
        }     
    }

  

  调用方式

DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
DatagridViewCheckBoxHeaderCell cbHeader = new DatagridViewCheckBoxHeaderCell();
colCB.HeaderCell = cbHeader;
datagridview1.Columns.Add(colCB);
cbHeader.OnCheckBoxClicked += 
    new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);

  1. 我们只需要定义一个DataGridViewCheckBoxColumn。

  2. 然后为每一行的checkbox 定义一个CheckboxClicked 事件。

 

  测试程序

  创建一个Winform 项目,加个datagridview控件,初始化几行默认数据。注意:datagirdview有编辑状态,如果有一行数据在编辑状态,那这一行被编辑。

  解决办法就是在事件的绑定方法里面增加EndEdit()调用。

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            InitDtSource();
        }

        private void cbHeader_OnCheckBoxClicked(bool state)
        {
            //这一句很重要结束编辑状态
            dgInfo.EndEdit();
            dgInfo.Rows.OfType<DataGridViewRow>().ToList().ForEach(t => t.Cells[0].Value = state);
        }

        private void InitDtSource()
        {
            try
            {
                var _dtSource = new DataTable();
                //1、添加列
                _dtSource.Columns.Add("姓名", typeof(string)); //数据类型为 文本
                _dtSource.Columns.Add("身份证号", typeof(string)); //数据类型为 文本
                _dtSource.Columns.Add("时间", typeof(string)); //数据类型为 文本
                _dtSource.Columns.Add("地点", typeof(string)); //数据类型为 文本

                for (int i = 0; i < 10; i++)
                {
                    DataRow drData = _dtSource.NewRow();
                    drData[0] = "test" + i;
                    drData[1] = "35412549554521263" + i;
                    drData[2] = "2017-05-21 10:55:21";
                    drData[3] = "北京市";
                    _dtSource.Rows.Add(drData);
                }

                dgInfo.DataSource = _dtSource;

                InitColumnInfo();
            }
            catch (Exception ex)
            {

            }
        }

        private void InitColumnInfo()
        {
            int index = 0;

            DataGridViewCheckBoxColumn colCB = new DataGridViewCheckBoxColumn();
            DatagridViewCheckBoxHeaderCell cbHeader = new DatagridViewCheckBoxHeaderCell();
            colCB.HeaderCell = cbHeader;
            colCB.HeaderText = "全选";
            cbHeader.OnCheckBoxClicked += new CheckBoxClickedHandler(cbHeader_OnCheckBoxClicked);
            dgInfo.Columns.Insert(index, colCB);


            index++;
            dgInfo.Columns[index].HeaderText = "姓名";
            dgInfo.Columns[index].Width = 90;

            index++;
            dgInfo.Columns[index].HeaderText = "身份证号";
            dgInfo.Columns[index].Width = 120;

            index++;
            dgInfo.Columns[index].HeaderText = "时间";
            dgInfo.Columns[index].Width = 150;

            index++;
            dgInfo.Columns[index].HeaderText = "地点";
            dgInfo.Columns[index].Width = 100;

            System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
            dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;//211, 223, 240
            dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Blue;
            dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.Blue;
            dgInfo.Columns[index].DefaultCellStyle = dataGridViewCellStyle2;
        }
    }

 

  其他

  1. 参考地址:https://www.codeproject.com/Articles/20165/CheckBox-Header-Column-For-DataGridView

  2. Demo下载

 


以上是关于datagridview 怎么在头一列加个全选?c#的主要内容,如果未能解决你的问题,请参考以下文章

checkbox有2个全选按钮,如何选择其中一个,另一个也自动选上,反之亦然

C#总结DataGridView增加全选列

c# datagridview 设置某列为日期

Excel中如何在一个列的所有值前面加个字母

C# DataGridView 检测全选按钮

我想请教你 我想实现 点击全选的时候 dev控件GridControl 中的每一列都被选中 并且我如何获取是不是选中