DataGridView: apply editing to all selected rows

I have a DataGridView associated with a list of POCO objects. One of the properties of POCO is bool, which is represented by a checkbox. I would like to be able to select multiple rows, and then when I click one of the checkboxes, all the highlighted rows have their own checkboxes. As an example, if you use TFS under VS 2010, I am trying to reproduce the behavior on the screen of pending changes.

My problem is that I cannot find a suitable event to listen to. Most clickGridView events seem to work at the Column / Row level, and I want something that fires when you click this checkbox. CellContentClick is the closest, but it fires after no rows have been selected so as not to work.

Does anyone have any suggestions?

+6
source share
2 answers

You can use CurrentCellDirtyStateChanged if the Checkbox value has been changed. But when this event fires, the selected ones will be deleted. All you have to do is keep the highlighted lines in front of it.

A simple example: you can easily complete it.

DataGridViewSelectedRowCollection selected; private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { DataGridView dgv = (DataGridView)sender; DataGridViewCell cell = dgv.CurrentCell; if (cell.RowIndex >= 0 && cell.ColumnIndex == 1) // My checkbox column { // If checkbox value changed, copy it value to all selectedrows bool checkvalue = false; if (dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue != null && dgv.Rows[cell.RowIndex].Cells[cell.ColumnIndex].EditedFormattedValue.Equals(true)) checkvalue = true; for (int i=0; i<selected.Count; i++) dgv.Rows[selected[i].Index].Cells[cell.ColumnIndex].Value = checkvalue; } dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { selected = dataGridView1.SelectedRows; } 
+10
source

This is not a nice design, but you can try using the MouseDown event (which will fire before the grid changes its selection) and HitTest (to find out where the user clicks):

 private void dataGridView1_MouseDown(object sender, MouseEventArgs e) { var hitTest = this.dataGridView1.HitTest(eX, eY); if (hitTest.Type == DataGridViewHitTestType.Cell && hitTest.ColumnIndex == 0 /* set correct column index */) { foreach (DataGridViewRow row in this.dataGridView1.Rows) { // Toggle row.Cells[0].Value = !((bool)row.Cells[0].Value); } } } 
+1
source

Source: https://habr.com/ru/post/910708/


All Articles