DataGridView retains filtering after reboot

I have some problems with a DataGridView in C #.

:

I update the database a bit, then reload the DataGridView with the new values:

myDataGridView.DataSource = myDataSet.Tables[0] 

Everything is in order, but recently I was asked if it is possible to maintain the same column filtering after data reloading?

What will be the approach for this filtering case?

Thanks for any ideas.

+4
source share
4 answers

Ok, I found a solution, maybe this will help someone: [By the way. I made some mistake in the language of the error = 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 the code from: link text

+11
source

I made a kuba decision and put it in a utility class that 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 this:

 GridUtility.SaveSorting(grid); grid.DataSource = databaseFetch(); // or whatever GridUtility.RestoreSorting(grid); 
+5
source

I met Adam Nofsinger's answer before I ran into a problem, but I used it anyway. It works great.

Just need to add these 2 using lines in my class file:

 using System.ComponentModel; using System.Windows.Forms; 

Thanks, Gert.

0
source

This worked for me:

 //preserve existing sort column and direction ListSortDirection direction; DataGridViewColumn oldsort = MyDataGridView.SortedColumn; if (MyDataGridView.SortOrder == SortOrder.Ascending) { direction = ListSortDirection.Ascending; } else { direction = ListSortDirection.Descending; } //this is refresh MyDataGridView.DataSource = data; //reapply sort and direction if (oldsort != null) { MyDataGridView.Sort(MyDataGridView.Columns[oldsort.Name], direction); } 
0
source

All Articles