Tuesday, March 20, 2012

C# - 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.



int  _cintHorizontalStop;
private void Grid_Scrolled(object sender, ScrollEventArgs e)
{
     
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
     {
          
 _cintHorizontalStop = e.NewValue;
     }
}
private void Grid_Sorted(object sender, EventArgs e)
{
     datagridview1.
HorizontalScrollingOffset =  _cintHorizontalStop ;
}

No comments:

Post a Comment