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; } }
C# sorting data in GridView for Windows Forms
ReplyDelete