I have some problem with DataGridView in C#.
case is:
I do some update on database then I reload DataGridView with new values:
myDataGridView.DataSource = myDataSet.Tables[0]
Everything is ok, but recently I was asked if there is possibility to keep the same column filtering applied after reloading data?
What would be approach to do this filtering case?
Thanks for any ideas.
Ok, I found the solution, maybe it will help somebody: [btw. I made some language mistake filtering = sorting ;-)]
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;
if (dataGridView1.SortOrder == SortOrder.Ascending) direction = ListSortDirection.Ascending;
else direction = ListSortDirection.Descending;
databaseUpdateFunction();
DataGridViewColumn newColumn = dataGridView1.Columns[oldColumn.Name.ToString()];
dataGridView1.Sort(newColumn,direction);
newColumn.HeaderCell.SortGlyphDirection =
direction == ListSortDirection.Ascending ?
SortOrder.Ascending : SortOrder.Descending;
I used parts of code from : link text
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;
/// <summary>
/// Saves information about sorting column, to be restored later by calling RestoreSorting
/// on the same DataGridView
/// </summary>
/// <param name="grid"></param>
public static void SaveSorting(DataGridView grid)
{
_oldSortOrder = grid.SortOrder == SortOrder.Ascending ?
ListSortDirection.Ascending : ListSortDirection.Descending;
_oldSortCol = grid.SortedColumn;
}
/// <summary>
/// Restores column sorting to a datagrid. You MUST call this AFTER calling
/// SaveSorting on the same DataGridView
/// </summary>
/// <param name="grid"></param>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With