1.在DataGridView中添加一条列,类型为DataGridViewCheckBoxColumn
2.添加CellClick事件编码如下
Code
1private void DataGridView1_CellClicked(object sender, DataGridViewCellEventArgs e)
2{
3 //-1的话则是标题被选中,如果没有这句,下面的容器将会越界出错
4 if (e.rowindex > -1 && e.ColumnIndex > -1)
5 {
6 //第一列的某个Cell被选中
7 if (e.ColumnIndex == 0)
8 {
9 //如果是选中状态,则取消。反之亦然
10 if ((bool)this.dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue)
11 {
12 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
13 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Empty;
14 }
15 else
16 {
17 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
18 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
19 }
20 }
21 }
22}
23
1private void DataGridView1_CellClicked(object sender, DataGridViewCellEventArgs e)
2{
3 //-1的话则是标题被选中,如果没有这句,下面的容器将会越界出错
4 if (e.rowindex > -1 && e.ColumnIndex > -1)
5 {
6 //第一列的某个Cell被选中
7 if (e.ColumnIndex == 0)
8 {
9 //如果是选中状态,则取消。反之亦然
10 if ((bool)this.dataGridView1.Rows[e.RowIndex].Cells[0].EditedFormattedValue)
11 {
12 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = false;
13 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Empty;
14 }
15 else
16 {
17 this.dataGridView1.Rows[e.RowIndex].Cells[0].Value = true;
18 this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Yellow;
19 }
20 }
21 }
22}
23