Skip to main content

How to Sort Rows in DevExpress Data Grid for .NET MAUI

  • 5 minutes to read

Users can click a grid column header to sort data in this column by its values. Subsequent clicks first change the sort order and then cancel sorting. If a user clicks multiple column headers, data is sorted by values in these columns in the order the headers were clicked.

DevExpress Data Grid for .NET MAUI - Sorting

Disable Sorting

Set the DataGridView.AllowSort property to false so that users cannot sort data in the grid. You can also disable a column’s GridColumn.AllowSort option to prevent users from sorting an individual column’s data.

The following example shows how to disable sorting for all columns except for the “Employee” column:

<dxg:DataGridView AllowSort="False">
    <dxg:DataGridView.Columns>
        <dxg:TemplateColumn FieldName="Name" Caption="Employee" AllowSort="True">
            <!--...-->
        </dxg:TemplateColumn>
    </dxg:DataGridView.Columns>
</dxg:DataGridView>

Sort Data in Multiple Columns

Set the DataGridView.SortMode property to Multiple to allow users to sort data by multiple columns.

The following example enables multi-column sorting in a grid:

<dxg:DataGridView SortMode="Multiple">
    <!--...-->
</dxg:DataGridView>

Sort Data in Code

The following column properties allow you to sort data in code:

GridColumn.SortOrder
Specifies the column’s sort order.
GridColumn.SortIndex
Specifies the column’s position among sorted columns.

You can also call the DataGridView.SortBy method to sort data by the specified column.

The ClearSorting method resets sorting applied to the grid.

Example

The following example shows how to sort data by the product name first and then by quantity. The example also disables sorting by values in the Shipped column.

Data Grid - Sorting

<dxg:DataGridView ItemsSource="{Binding Orders}" 
                  SortMode="Multiple">
        <dxg:DataGridView.Columns>
            <dxg:TextColumn FieldName="Product.Name" Caption="Product" Width="150"
                            SortOrder="Descending" SortIndex="0"/>
            <dxg:NumberColumn FieldName="Product.UnitPrice" Caption="Price" 
                              DisplayFormat="C0" MinWidth="100"/>
            <dxg:NumberColumn FieldName="Quantity" MinWidth="100"
                              SortOrder="Ascending" SortIndex="1"/>
            <dxg:NumberColumn FieldName="Total" 
                              UnboundType="Integer" UnboundExpression="[Quantity] * [Product.UnitPrice]" 
                              IsReadOnly="True" DisplayFormat="C0" MinWidth="100"/>
            <dxg:DateColumn FieldName="Date" DisplayFormat="d" MinWidth="100"/>
            <dxg:CheckBoxColumn FieldName="Shipped" MinWidth="100" 
                                AllowSort="False"/>
        </dxg:DataGridView.Columns>
</dxg:DataGridView>

Drag Sorted Rows

To allow drag and drop operations, enable the DataGridView.AllowDragDropRows property. Enable the DataGridView.AllowDragDropSortedRows option so users can drag rows to a new position. This capability is useful if you group grid data. You can drag a row between groups. If you drop a row into a different group, the control updates the row’s data accordingly.

For more information, refer to the following section: Drag and Drop Rows.

Sort Rows Based on a Custom Rule

To apply a custom sorting rule to a grid column, set the column’s SortMode property to Custom and then handle the grid’s CustomSort event.

The CustomColumnSort event allows you to compare two rows by their values and decide which row should be positioned first based on the comparison result.

The CustomSortEventArgs.Column property returns the column that is being processed. The CustomSortEventArgs.SourceIndex1 and CustomSortEventArgs.SourceIndex2 properties return the indexes of the rows that are compared. The cell values used to compare rows are specified by the CustomSortEventArgs.Value1 and CustomSortEventArgs.Value2 properties.

After the rows are compared, specify the CustomSortEventArgs.Result property to set the result of row comparison:

  • Set Result to -1 if the first row should be positioned above the second row. When data is sorted in descending order, the first row is positioned below the second row.
  • Set Result to 1 if the first row should be positioned below the second row. When data is sorted in descending order, the first row is positioned above the second row.
  • Set Result to 0 to indicate that the rows are equal. In this case, the rows are arranged in the grid according to their indexes in the data source.

Use the GridColumn.SortOrder property to set the sort order.

The following example groups integers in the numeric grid column by parity:

DevExpress MAUI Grid - Custom Groups

To group rows as in the grid above, follow the steps below:

  1. Handle the DataGridView.CustomSort event to sort values in a custom manner. If users sort data in ascending order, the grid displays even numbers first, then odd numbers. Set the DataGridView.SortMode property to Custom to apply the custom sort algorithm.

  2. Enable the GridColumn.IsGrouped property for a column whose values you want to use to group rows. Handle the DataGridView.CustomGroup event to apply a custom grouping algorithm. This example divides column values into two groups of even and odd values. To show the group column, set the DataGridView.ShowGroupedColumns property to True.

  3. Handle the DataGridView.CustomGroupDisplayText event to format group captions based on a condition. In this example, the display text is set based on the Value property value. The Value property contains the value of the first row in the group.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:dxg="clr-namespace:DevExpress.Maui.DataGrid;assembly=DevExpress.Maui.DataGrid"
             xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls"
             xmlns:local="clr-namespace:CustomGroups" 
             x:Class="CustomGroups.MainPage">
    <ContentPage.BindingContext>
        <local:GridViewModel/>
    </ContentPage.BindingContext>
    <dxg:DataGridView x:Name="grid" ItemsSource="{Binding Data}" 
                      CustomSort="grid_CustomColumnSort" 
                      CustomGroup="grid_CustomColumnGroup" 
                      CustomGroupDisplayText="grid_CustomGroupDisplayText" 
                      ShowGroupedColumns="True" SelectionMode="None">
        <dxg:DataGridView.Columns>
            <dxg:NumberColumn FieldName="Number" Caption="Number" 
                              SortMode="Custom" SortOrder="Ascending" 
                              IsGrouped="True" HorizontalContentAlignment="Start" />
        </dxg:DataGridView.Columns>
    </dxg:DataGridView>
</ContentPage>
using DevExpress.Maui.DataGrid;

namespace DXMauiApp1 {
    public partial class MainPage : ContentPage {
        public MainPage() {
            InitializeComponent();
        }

        private void grid_CustomColumnSort(object sender, CustomSortEventArgs e) {
            if (e.Column.FieldName != "Number") return;
            var v1 = (int)e.Value1;
            var v2 = (int)e.Value2;
            var even1 = v1 % 2 == 0;
            var even2 = v2 % 2 == 0;
            if (even1 ^ even2)
                e.Result = even1 ? -1 : 1;
            else e.Result = Comparer<int>.Default.Compare(v1, v2);
        }

        private void grid_CustomColumnGroup(object sender, CustomGroupEventArgs e) {
            if (e.Column.FieldName != "Number") return;
            var v1 = (int)e.Value1;
            var v2 = (int)e.Value2;
            var isEven1 = v1 % 2 == 0;
            var isEven2 = v2 % 2 == 0;
            e.GroupsEqual = !(isEven1 ^ isEven2);
        }

        private void grid_CustomGroupDisplayText(object sender, CustomGroupDisplayTextEventArgs e) {
            if (e.Column.FieldName != "Number") return;
            e.DisplayText = ((int)e.Value % 2 == 0 ? "Even" : "Odd");
        }
    }

    public class GridViewModel {
        int itemCount = 10;
        Random rnd = new Random();
        public ObservableCollection<DataEntry> Data { get; private set; }
        public GridViewModel() {
            Data = new ObservableCollection<DataEntry>();
            for (int i = 0; i < itemCount; i++) {
                Data.Add(new DataEntry(rnd.Next(0, 100)));
            }
        }
        public class DataEntry {
            public int Number { get; private set; }
            public DataEntry(int number) {
                Number = number;
            }
        }
    }
}

Enable Live Data Recalculation

Enable the DataGridView.AllowLiveDataShaping property to recalculate DataGridView values and refresh it when users filter, group, and sort data.

See Also