C# DataGridView 新增 checkbox 及設定全選、全部取消功能
新增欄位時,先在第0欄建立一個空欄位,接下來移除再插入checkbox
...
yourDGV.DataSource = dt;
...
yourDGV.Columns[0].HeaderText = "";
...
for (int i = 0; i <= yourDGV.ColumnCount - 1; i++)
{
//可以像這樣一次調整多個column
yourDGV.Columns[i].ReadOnly = true;
yourDGV.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
}
int colCount = yourDGV.ColumnCount;
for (int i = 0; i < colCount; i++)
{
if (i == (colCount - 1))
{
yourDGV.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
else
{
yourDGV.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; // YS:改成可調整欄位大小(下一行)
}
}
// [ 增加 checkbox]
DataGridViewColumn colCheck = new DataGridViewCheckBoxColumn();
colCheck.Width = 45;
yourDGV.Columns.RemoveAt(0);//change first column to checkbox
yourDGV.Columns.Insert(0, colCheck);
yourDGV.Columns[0].HeaderText = "選取";
下方 CheckboxAllSelected 方法可以用來設定目標 DataGridView 指定欄位是否選取或取消
//全部選取
CheckboxAllSelected(yourDGV, true);
//全部取消
CheckboxAllSelected(yourDGV, false);
// Checkbox 全選/取消 Methods
private void CheckboxAllSelected(DataGridView dgv_tg, Boolean checkd_status)
{
for(int i = 0; i < dgv_tg.RowCount; i++)
{
dgv_tg.Rows[i].Cells[0].Value = checkd_status;
}
}