1 DataGridViewCheckBoxColumn dtCheck = new DataGridViewCheckBoxColumn();
2 dtCheck.DataPropertyName = "check";
3 dtCheck.HeaderText = "";
4 dataGridView1.Columns.Add(dtCheck);
5 dataGridView1.DataSource = DataTable; 6
以上代碼 是在DataGridView中添加復選框
1 private void chkBox_CheckedChanged(object sender, EventArgs e) 2 { 3 if (this.chkBox.Checked == true) 4 { 5 for (int i = 0; i < dataGridView1.Rows.Count; i++) 6 { 7 this.dataGridView1.Rows[i].Cells[0].Value = true; 8 } 9 } 10 else 11 { 12 for (int i = 0; i < dataGridView1.Rows.Count; i++) 13 { 14 this.dataGridView1.Rows[i].Cells[0].Value = false; 15 } 16 } // this.dataGridView1.Rows[i].Cells[0].Value =false; 17 18 }
以上是一個CheckBox 單擊事件 用作於 全選/反選
1 DataTable dt = (DataTable)dataGridView1.DataSource; 2 //使用方法 3 foreach(DataRow row in dt.Rows) 4 { 5 if (row["check"].ToString() == "True") 6 { 7 //處理方式 8 } 9 }
以上是后台代碼操作過程 被選中的CheckBox 自己想怎么處理就怎么寫
注:如果需要使復選框不能多選時,將DataGridView 的CellValueChanged事件和CurrentCellDirtyStateChanged事件

1 private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) 2 { 3 DataGridView dgv = (DataGridView)sender; 4 if (dgv.IsCurrentCellDirty) 5 { 6 dgv.CommitEdit(DataGridViewDataErrorContexts.Commit); 7 } 8 } 9 private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 10 { 11 if (e.ColumnIndex == 0) 12 { 13 DataGridView dgv = (DataGridView)sender; 14 DataTable dt = (DataTable)dgv.DataSource; 15 DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv.Rows[e.RowIndex].Cells[0]; 16 bool value = (Boolean)checkCell.Value; 17 for (int i = 0; i < dt.Rows.Count; i++) 18 { 19 DataRow row = dt.Rows[i]; 20 if (i != e.RowIndex && value) 21 { 22 row["check"] = false; 23 } 24 } 25 dgv.Invalidate(); 26 } 27 }
========================================================================================================
dataGridView1中復選框批量選中
1、dataGridView1.SelectionMode = 'FullRowSelect ' // dataGridView1 可以選中整行
2、添加一個contextMenuStrip1 控件 //右鍵菜單
選擇 的name = 'SelectToolStripMenuItem'
3、dataGridView1添加CellMouseDown事件 代碼如下
1 private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) 2 { 3 if (e.Button == MouseButtons.Right) 4 { 5 if (e.RowIndex >= 0) 6 { 7 //若行已是選中狀態就不再進行設置 8 if (dataGridView1.Rows[e.RowIndex].Selected == false) 9 { 10 dataGridView1.ClearSelection(); 11 dataGridView1.Rows[e.RowIndex].Selected = true; 12 } 13 //只選中一行時設置活動單元格 14 if (dataGridView1.SelectedRows.Count == 1) 15 { 16 dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]; 17 } 18 //彈出操作菜單 19 contextMenuStrip1.Show(MousePosition.X, MousePosition.Y); 20 } 21 } 22 }
4、添加SelectToolStripMenuItem的Click 事件 代碼如下
1 private void SelectToolStripMenuItem_Click(object sender, EventArgs e) 2 { 3 foreach (var item in this.dataGridView1.SelectedRows) 4 { 5 int i = ((System.Windows.Forms.DataGridViewBand)((DataGridViewRow)item)).Index; 6 7 this.dataGridView1.Rows[i].Cells[0].Value = true; 8 9 } 10 }
這樣 我們就完成批量選中復選框的功能了