Wednesday, March 14, 2012

VB.NET - Maintain Position on DataGridView After Column Sort

The following code handles the situation when the user is in a DataGridView and they sort a column while scrolled over.   By default, if the user sorts the column it will snap the user back over to the left. This code will allow the user to maintain the position they are in.  First whenever the scroll event is activated, a modular level variable stores the stop position of the horizontal scroll bar.  Whenever a user sorts a column in the grid the horizontal scroll bar position is set to the modular level variable that was set in the prior event.

Private _cintHorizontalStop  As Integer '<-- modular level variable



Private Sub datagridview1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles  datagridview1 .Scroll
        Try
            If e.ScrollOrientation = ScrollOrientation.HorizontalScroll Then
                  _cintHorizontalStop   = e.NewValue
            End If
        Catch ex As Exception
            ErrorHandlerMuni(ex)
        End Try
    End Sub


    Private Sub  datagridview1 _Sorted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  datagridview1 .Sorted
        Try
            gridDGV.HorizontalScrollingOffset = _cintHorizontalStop  
        Catch ex As Exception
            ErrorHandlerMuni(ex)
        End Try
    End Sub

No comments:

Post a Comment