Code Snippet
' Global list to save selected indexes
Private mSelectedRows As Collections.Generic.List(Of Integer) = New Collections.Generic.List(Of Integer)
Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
Dim iIndex As Integer
' Reset information on saved selected indexes
mSelectedRows.Clear()
' Don't save selection of Shift or Ctrl key is used to alter selection
If Not (My.Computer.Keyboard.CtrlKeyDown OrElse My.Computer.Keyboard.ShiftKeyDown) Then
' Get index of row clicked and check if it's selected
iIndex = e.RowIndex
If iIndex >= 0 AndAlso DataGridView1.Rows(iIndex).Selected Then
' Save indexes of all selected rows to list
For Each oRow As DataGridViewRow In DataGridView1.SelectedRows
mSelectedRows.Add(oRow.Index)
Next
End If
End If
End Sub
Private Sub DataGridView1_SelectionChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles DataGridView1.SelectionChanged
Static bRestoringSelection As Boolean = False
' Flag to prevent recursion of this event
If bRestoringSelection Then Exit Sub
' Check if saved indexes of selected rows exist
If mSelectedRows.Count > 0 Then
Dim oRows As Collections.Generic.List(Of Integer)
' Set recursion flag and suspend visual updates
bRestoringSelection = True
DataGridView1.SuspendLayout()
' Restore selection
For Each iIndex As Integer In oRows
DataGridView1.Rows(iIndex).Selected = True
Next
' Clear information on saved selection indexes
mSelectedRows.Clear()
' Resume layout and reset recursion flag
DataGridView1.ResumeLayout()
bRestoringSelection = False
End If
End Sub