Select multiple rows in a C# DataGridView programmatically?
Posted on 2013-12-09
I need to select multiple rows in a DataGridView (MultiSelect = true, SelectionMode = RowHeaderSelect). From the user interface there is no problem. I simply hold down the <CTRL> key and click on all of the row headers one-by-one. When I click on a row, all of the cells in the row are redrawn with a blue background indicating that they have been selected and the arrow that appears in the row header column is updated so that it is in the last row header that I clicked.
When attempting to replicate this behavior programmaticly I run into a problem. The code shown below is supposed to do this - first it fills the DataGridView with data (the DataGridView is not DataBound) and second it selects all of the rows. The System.Diagnostics lines output what I would expect when there are 3 rows in the DataGridView; before = 0 and after = 3. However, on the UserInterface the background of the cells in the first row are blue but the cells in the second and third rows are white and the triangle is still sitting in the row header of the first row. I expected it to be in the row header of the third row.
I tried to select all cells of all rows using the line that has been commented-out in the second loop of the code below but that didn't solve my problem.
Any thoughts on how to fix this (without making the DataGridView DataBound)?
public void displayMeasurements(List<clsMeasurement> L_Msrmt)
foreach (clsMeasurement Msrmt in L_Msrmt)
int row = DGV.Rows.Add();
DGV.Rows[row].Cells["col_x"].Value = Msrmt.x;
DGV.Rows[row].Cells["col_y"].Value = Msrmt.y;
DGV.Rows[row].Cells["col_x"].Value = Msrmt.y;
DGV.Rows[row].Tag = Msrmt;
System.Diagnostics.Trace.WriteLine("before = " + DGV.SelectedRows.Count.ToString());
foreach (DataGridViewRow r in DGV.Rows)
r.Selected = true;
//foreach (DataGridViewCell c in r.Cells) c.Selected = true;
System.Diagnostics.Trace.WriteLine("after = " + DGV.SelectedRows.Count.ToString());