I have some problem with DataGridView in C#.
case is:
I do some update on database then I reload DataGridView with new values:
myDataGridView.Dat
I took kuba's solution, and put it in a utility class I can use on any DataGridView
:
private static ListSortDirection _oldSortOrder;
private static DataGridViewColumn _oldSortCol;
///
/// Saves information about sorting column, to be restored later by calling RestoreSorting
/// on the same DataGridView
///
///
public static void SaveSorting(DataGridView grid)
{
_oldSortOrder = grid.SortOrder == SortOrder.Ascending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
_oldSortCol = grid.SortedColumn;
}
///
/// Restores column sorting to a datagrid. You MUST call this AFTER calling
/// SaveSorting on the same DataGridView
///
///
public static void RestoreSorting(DataGridView grid)
{
if (_oldSortCol != null)
{
DataGridViewColumn newCol = grid.Columns[_oldSortCol.Name];
grid.Sort(newCol, _oldSortOrder);
}
}
Using this looks like:
GridUtility.SaveSorting(grid);
grid.DataSource = databaseFetch(); // or whatever
GridUtility.RestoreSorting(grid);