DataGridView save filtering after reload

前端 未结 4 2118
春和景丽
春和景丽 2021-02-10 20:34

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         


        
4条回答
  •  死守一世寂寞
    2021-02-10 21:15

    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);
    

提交回复
热议问题