2 Datagridview full row select

evolet10000

Active member
Joined
Nov 22, 2012
Messages
40
Programming Experience
Beginner
i have 2 datagridviews, what i want to achieve is whenever the user clicks a row(selectionmode = fullrowselect) in dgv1 the same row will also be selected in dgv2(selectionmode = fullrowselect) ,
the same goes when the user clicks on dgv2.,

thanks in advance :D
 
This is how I'd do it. One event handler for both grids, get the indexes of the selected rows from the grid that raises the event, select same row indexes in other grid (including unselecting rows):
    Private ignoreSelectionChanged As Boolean

    Private Sub Grids_SelectionChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.SelectionChanged, DataGridView2.SelectionChanged
        If Not ignoreSelectionChanged Then
            ignoreSelectionChanged = True

            Dim grid = CType(sender, DataGridView)
            Dim othergrid = If(grid Is DataGridView1, DataGridView2, DataGridView1)
            Dim selectedIndices = From row In grid.SelectedRows.Cast(Of DataGridViewRow)() Select row.Index
            For Each row In othergrid.Rows.Cast(Of DataGridViewRow)()
                row.Selected = selectedIndices.Contains(row.Index)
            Next

            ignoreSelectionChanged = False
        End If
    End Sub

ignoreSelectionChanged variable was added to filter out events when the manual selections takes place.

To sync the displayed rows if there is scrolling you can also add this:
othergrid.FirstDisplayedScrollingRowIndex = grid.FirstDisplayedScrollingRowIndex
 
Back
Top