Lesson 5: Sort Data

  • 2 minutes to read

DataGridView allows end users to sort data by a single column. To sort data by the specified column, set the GridColumn.SortOrder property to ColumnSortOrder.Ascending or ColumnSortOrder.Descending.

You can also sort data records by multiple columns. To do this, set the DataGridView.SortMode property to GridSortMode.Multiple, and specify GridColumn.SortOrder for each column to be sorted. To specify the sorting sequence applied to columns, use the GridColumn.SortIndex property of these columns.

To prevent end users from sorting data by a specific column, use the GridColumn.AllowSort property.

Open the solution created in Lesson 4 and apply the following sort settings:

  • Sort orders displayed in the grid by the Product.Name column first and then by the Quantity column.
  • Disable sorting by the Shipped column.

You can specify grid sorting settings in XAML...

<dxg:DataGridView x:Name="grid" ItemsSource="{Binding Orders}" 
                 CalculateCustomSummary="OnCalculateCustomSummary" 
                 SortMode="Multiple">
    <dxg:DataGridView.Columns>
        <dxg:TextColumn FieldName="Product.Name" Caption="Product" Width="150" 
                        SortOrder="Descending" SortIndex="0"/>
        <!-- ... -->
        <dxg:NumberColumn FieldName="Quantity" MinWidth="100" 
                          SortOrder="Ascending" SortIndex="1"/>
        <!-- ... -->
        <dxg:CheckBoxColumn FieldName="Shipped" MinWidth="100" AllowSort="False"/>
    </dxg:DataGridView.Columns>
</dxg:DataGridView>

... or C# code.

grid.SortMode = GridSortMode.Multiple;

grid.Columns ["Product.Name"].SortOrder = DevExpress.Data.ColumnSortOrder.Descending;
grid.Columns ["Product.Name"].SortIndex = 0;

grid.Columns ["Quantity"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
grid.Columns ["Quantity"].SortIndex = 1;

grid.Columns ["Shipped"].AllowSort = DevExpress.Utils.DefaultBoolean.False;

Orders in the grid are now sorted by products first and then by the number of product units. Users can tap column headers to sort data in the grid.

Sort Data

The next lesson explains how to filter data in the grid.