Wednesday, September 19, 2012

WPF DataGrid - Column Sorting

Small note for column sorting in WPF DataGrid control. How can we show data in DataGrid initially in descending order? If a column is in descending order, two things should be done. Firstly, the data should be sorted accordingly, that is, descending order. Secondly, the header of the column is supposed to show down arrow mark which represents "descending order."

To show down arrow mark in column header, add SortDirection attribute to the column. In example below, "ID" column has SortDirection=Descending attribute.

<DataGrid Name="dataGrid1" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"
             SortDirection="Descending" />
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
    </DataGrid.Columns>
</DataGrid>

To actually show sorted data, your data source should be sorted in descending order. If your data source is SQL data source, best way is doing it in SQL ORDER BY statement. If your data source is in memory collection, LINQ might be good way of doing sorting. Another approach is to use SortDescriptions property in DataGrid.Items as you can see below. The code below added ID as sorting column in descending order.
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<MyData> myItems = new List<MyData>();
        myItems.Add(new MyData(1, "Lee"));
        myItems.Add(new MyData(2, "kim"));

        dataGrid1.Items.SortDescriptions.Add(
new SortDescription("ID", ListSortDirection.Descending));
        dataGrid1.ItemsSource = myItems;
    }
}

public class MyData
{
    public int ID { get; set; }
    public string Name { get; set; }
    public MyData() { }
    public MyData(int id, string name)
    {
        this.ID = id;
        this.Name = name;
    }
}

1 comment: