.Net Grid sorting depends on headers. Sorted columns are stored in Header.SortedColumns. To enable sorting you have to use Column.SortDirection property. Calling this property for multiple columns sets multiple sorting by these columns. To cancel sorting, call Header.SortedColumns.Clear().

C# Copy imageCopy
public void SortedColumnsExample(Grid grid)
{
    //Add a new header on the top hierarchical level (level 0)
    Header header = new Header();
    header.Add(new Column("Column1"));
    header.Add(new Column("Column2"));
    header.Add(new Column("Column3"));
    grid.Headers.Add(header);

    Console.WriteLine("Sorted columns count: {0}", header.GroupedColumns.Count);

    header.SortedColumns.Clear();

    //Set multiple sort by two columns
    header["Column1"].SortDirection = SortDirection.Ascending;
    header["Column3"].SortDirection = SortDirection.Ascending;

    Console.WriteLine("Columns count: {0}", header.Count);
    Console.WriteLine("Sorted columns count: {0}", header.SortedColumns.Count);

    //Change the sort direction
    header["Column3"].SortDirection = SortDirection.Descending;

    //Iterate in all sorted columns
    foreach (Column column in header.SortedColumns)
    {
        Console.WriteLine("Sorted column: id = '{0}', index = {1}, visible index = {2}, sort level = {3}, sort direction = {4}", column.Id, column.Index, column.VisibleIndex, column.SortLevel, column.SortDirection);
    }

    //Remove sort
    header.SortedColumns.Clear();
    Console.WriteLine("Columns count: {0}", header.Count);
    Console.WriteLine("Sorted columns count: {0}", header.SortedColumns.Count);
}

//Output:
//Sorted columns count: 0
//Columns count: 3
//Sorted columns count: 2
//Sorted column: id = 'Column1', index = 0, visible index = 0, sort level = 0, sort direction = Ascending
//Sorted column: id = 'Column3', index = 2, visible index = 2, sort level = 1, sort direction = Descending
//Columns count: 3
//Sorted columns count: 0

Back to .Net Grid HowTo topics