C#_winform_GridView_CheckBox_多选_全选

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace CBoxInGV
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            gvBind();//取数据

            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.PaleTurquoise;      //奇數列顏色

            //先建立個 CheckBox 欄
            DataGridViewCheckBoxColumn cbCol = new DataGridViewCheckBoxColumn();
            cbCol.Width = 50;   //設定寬度
            cbCol.HeaderText = " 全选";
            cbCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;   //置中
            dataGridView1.Columns.Insert(0, cbCol);

            #region 建立全选 CheckBox

            //建立個矩形,等下計算 CheckBox 嵌入 GridView 的位置
            Rectangle rect = dataGridView1.GetCellDisplayRectangle(0, -1, true);
            rect.X = rect.Location.X + rect.Width / 4 - 9;
            rect.Y = rect.Location.Y + (rect.Height / 2 - 9);

            CheckBox cbHeader = new CheckBox();
            cbHeader.Name = "checkboxHeader";
            cbHeader.Size = new Size(18, 18);
            cbHeader.Location = rect.Location;
            //全選要設定的事件
            cbHeader.CheckedChanged += new EventHandler(cbHeader_CheckedChanged);

            //將 CheckBox 加入到 dataGridView
            dataGridView1.Controls.Add(cbHeader);

            #endregion

        }
        /// <summary>
        /// 取数据
        /// </summary>
        private void gvBind()
        {
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("编号", typeof(int));
            dt1.Columns.Add("姓名", typeof(string));
            dt1.Columns.Add("年龄", typeof(int));
            dt1.Columns.Add("性别", typeof(string));

            dt1.Rows.Add(1, "小王", 20, "男");
            dt1.Rows.Add(2, "王小儿", 30, "男");
            dt1.Rows.Add(3, "李大妈", 40, "女");
            dt1.Rows.Add(4, "王大嫂", 50, "女");
            dt1.Rows.Add(5, "李敏", 60, "女");
            dt1.Rows.Add(6, "老李", 70, "男");

            dataGridView1.DataSource = dt1;
        }

        private void cbHeader_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dr in dataGridView1.Rows)
                dr.Cells[0].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
        }
    }
}

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值