Search code examples
c#wpfxamlsortingwpfdatagrid

Retain the user defined sort order in WPF DataGrid


I have a WPF DataGrid that is populated with data from DataSet. I have CanUserSortColumns set to true.

Is it possible to retain the sorting that the user specified when the grid is refreshed? I have it retaining the item that was selected using

  object selectedItem = dgInvoiceHeads.SelectedItem;

before the refresh takes place and then placing

 dgInvoiceHeads.SelectedItem = selectedItem;

after the refresh takes place.

But I can't seem to get it to retain the specified sort.


Solution

  • One of my colleagues came up with this. It seems to be working correctly. The only thing is I think the column headers need to be the same in the DataGrid as they are in the DB.

    string sortHeader;
    string prevSortHeader;
    SortDescription sd;
    
    private void dgInvoiceHeads_Sorting(object sender, DataGridSortingEventArgs e) {
      sortHeader = e.Column.Header.ToString();
    
      if (sortHeader == prevSortHeader) {
        sd = new SortDescription(sortHeader, ListSortDirection.Descending);
      }
      else {
        sd = new SortDescription(sortHeader, ListSortDirection.Ascending);
      }
      prevSortHeader = sortHeader;
    }
    

    HTH