目標:
一、選中全選這個復選框,會選中第一列所有的復選框
拉過來一個CheckBox控件(CheckBox1)覆蓋在第一列的標題上,文本值:全選
方法:雙擊上面拉的CheckBox控件,進入其事件
private void checkBox1_CheckedChanged(object sender, EventArgs e) { int count = dataGridView1.Rows.Count; for (int i = 0; i < count; i++) { DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0]; Boolean flag = Convert.ToBoolean(checkCell.Value); if (flag == false) { checkCell.Value = true; } else { continue; } } }
即可實現:
取被選中的那一行的某列的值:
string aaa= ""; int count = dataGridView1.Rows.Count; for (int i = 0; i < count; i++) { DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0]; Boolean flag = Convert.ToBoolean(checkCell.Value); if (flag == true) { aaa= this.dataGridView1.Rows[i].Cells[2].Value.ToString(); } }
這就是取被選中的那一行的第三列的值
目標:
二、取消所有選中的復選框,CheckBox1未選中的情況下,取消第一列所有已選中的
方法:
private void checkBox1_CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { int count = dataGridView1.Rows.Count; for (int i = 0; i < count; i++) { DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0]; Boolean flag = Convert.ToBoolean(checkCell.Value); if (flag == false) { checkCell.Value = true; } else { continue; } } } else { int count = dataGridView1.Rows.Count; for (int i = 0; i < count; i++) { DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dataGridView1.Rows[i].Cells[0]; Boolean flag = Convert.ToBoolean(checkCell.Value); if (flag == true) { checkCell.Value = false; } else { continue; } } } }