private void Form1_Load(object sender, EventArgs e)
{
DataGridViewColumn dgvc = new DataGridViewCheckBoxColumn();
dgvc.Width = 40;
dgvc.Name = " ";
this.dataGridView1.AllowUserToAddRows = false;
dataGridView1.Columns.Insert(0, dgvc);
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);
}
private void cbHeader_CheckedChanged(object sender, EventArgs e)
{
// 避免編輯的資料因為 EditMode 狀態,不能正常勾選
dataGridView1.EndEdit();
foreach (DataGridViewRow dr in dataGridView1.Rows)
dr.Cells[0].Value = ((CheckBox)dataGridView1.Controls.Find("checkboxHeader", true)[0]).Checked;
}
參考資料:
http://jengting.blogspot.tw/2016/07/DataGridView-DataGridViewCheckBoxColumn-HeaderCell-CheckBox-SelectAll.html
https://dotblogs.com.tw/shunnien/2013/07/22/111941