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 }