0

I have a DataGrid shown a DataView with some values, sales figures for example, like

id | name | sales
15 | Smith | 100
16 | Mueller | 150
17 | Andrews | 75

And in this DataView is also a single row with sums like
0 | total | 325

Is it possible to integrate a custom sort (by click on columnHeader), but to have the sum row everytime as first row? In sql I achieve this with something like that: ORDER BY IF(id = 0, 0, 1), [columnName]. Can I get this in a DataGrid too? I didn't find out how. Thx ...

1
  • please share what you have tried so far. Commented Feb 26, 2018 at 9:51

1 Answer 1

2

I figured it out myself. I add a computed column to my table:

tabView.Table.Columns.Add("_sort", typeof(int));
tabView.Table.Columns["_sort"].Expression = "iif(id = 0, 0, 1)";

And the sorting event on a click on the columnheader looks like

private static void Grid_Sorting(object sender, DataGridSortingEventArgs e)
{
    var grid = ((DataGrid)sender);
    var cView = CollectionViewSource.GetDefaultView(grid.ItemsSource);

    //Alternate between ascending/descending if the same column is clicked 
    var direction = ListSortDirection.Ascending;
    if (cView.SortDescriptions.Count >= 2 && cView.SortDescriptions[1].PropertyName == e.Column.SortMemberPath)
        direction = cView.SortDescriptions[1].Direction == ListSortDirection.Descending ? ListSortDirection.Ascending : ListSortDirection.Descending;

    cView.SortDescriptions.Clear();
    cView.SortDescriptions.Add(new SortDescription("_sort", ListSortDirection.Ascending));
    grid.Columns.First(c => c.SortMemberPath == "_sort").SortDirection = ListSortDirection.Ascending;
    cView.SortDescriptions.Add(new SortDescription(e.Column.SortMemberPath, direction));
    grid.Columns.First(c => c.SortMemberPath == e.Column.SortMemberPath).SortDirection = direction;

    e.Handled = true;
}


thx to this helpful entry

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.