Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView save filtering after reload

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.

like image 943
kuba Avatar asked Aug 13 '10 10:08

kuba


2 Answers

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

like image 156
kuba Avatar answered Oct 04 '22 00:10

kuba


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);
like image 33
Adam Nofsinger Avatar answered Oct 04 '22 02:10

Adam Nofsinger