Sync horizontal scroll event of two DataGridViews
Asked Answered
P

2

6

I need to synchronize the scroll event of two DataGridView controls, so that when I horizontally scroll the first DGV, second DGV also should be scrolled in the same way.

Is it possible? Could this be set in design time?

Pennywise answered 28/6, 2014 at 12:16 Comment(1)
Do you want this to be a two way sync?Laurenalaurence
L
11

This can be done in code as follows. You may be looking for a C# way of doing it. But following is a code I used in a VB.NET application. Just convert it to C# ;)

For First Grid write...

Private Sub DataGridView1_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DataGridView1.Scroll

        If e.ScrollOrientation = ScrollOrientation.VerticalScroll Then Exit Sub
        If Me.DataGridView2.Rows.Count > 0 And Me.DataGridView1.Rows.Count > 0 Then
            Me.DataGridView2.HorizontalScrollingOffset = e.NewValue 'Me.DataGridView1.HorizontalScrollingOffset
        End If

End Sub

For Second Grid write...

Private Sub DataGridView2_Scroll(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles DataGridView2.Scroll

        If e.ScrollOrientation = ScrollOrientation.VerticalScroll Then Exit Sub
        If Me.DataGridView1.Rows.Count > 0 And Me.DataGridView2.Rows.Count > 0 Then
            Me.DataGridView1.HorizontalScrollingOffset = e.NewValue 'Me.DataGridView2.HorizontalScrollingOffset
        End If

End Sub

Hope this helped?

Laurenalaurence answered 28/6, 2014 at 12:29 Comment(0)
F
0

Here's a C# example; translated from @CAD's answer

If using Visual Studio, you can create a blank function easily by clicking the blank cell next to "Scroll" in listeners.

scroll listener

Then add the same to both:

private void dataGridViewLeft_Scroll(object sender, ScrollEventArgs e)
{
    if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll && dataGridViewLeft.Rows.Count > 0 && dataGridViewRight.Rows.Count > 0)
    {
        dataGridViewRight.HorizontalScrollingOffset = dataGridViewLeft.HorizontalScrollingOffset;
    }
}

private void dataGridViewRight_Scroll(object sender, ScrollEventArgs e)
{
    if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll && dataGridViewRight.Rows.Count > 0 && dataGridViewLeft.Rows.Count > 0)
    {
        dataGridViewLeft.HorizontalScrollingOffset = dataGridViewRight.HorizontalScrollingOffset;
    }
}
Finegrained answered 29/8, 2022 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.