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;
}
}
}