Skip to main content
All docs
V24.2

Sort Data in Blazor Grid

  • 7 minutes to read

The Grid can sort data by multiple columns. The sort glyph indicates the current sort order (ascending or descending).

Blazor Grid Sort Data

Run Demo Watch Video

The sort algorithm is applicable to data types that implement the IComparable interface. If a column data type does not support this interface, implement a custom sort algorithm.

Sort Data in the UI

The following user operations are available:

  • Click a column header to sort data in ascending order and clear sort criteria for all other columns. Subsequent clicks reverse the sort order.
  • Hold Shift and click column headers to sort data by multiple columns.
  • Hold Ctrl and click a column header to clear sorting by this column.

Users can focus a column header and press Space, Shift+Space, or Ctrl+Space to change sort settings. Refer to the following topic for more information on keyboard shortcuts: Keyboard Support in Blazor Grid.

You can use the following properties to prohibit end-user data sorting operations:

DxGrid.AllowSort
Specifies whether users can sort grid data.
DxGridDataColumn.AllowSort
Specifies whether users can sort data by the current column.

The following code snippet sorts data by the ContactName column and prevent users from clearing sort settings:

<DxGrid Data="Data" >
    <Columns>
        <DxGridDataColumn FieldName="ContactName" SortIndex="0" AllowSort="false" />
        <DxGridDataColumn FieldName="CompanyName" />
        <DxGridDataColumn FieldName="City" />
        <DxGridDataColumn FieldName="Region" />
        <DxGridDataColumn FieldName="Country" />
    </Columns>
</DxGrid>

Sort Data in Code

Specify Initial Sort Settings

You can use the following properties to specify a data column’s initial sort settings:

SortOrder
Specifies the column’s sort order (ascending or descending).
SortIndex
Specifies the column’s index among sorted columns. If the property is set to -1, the grid data is not sorted by this column.
<DxGrid Data="countryInfo">
    <Columns>
        <DxGridDataColumn FieldName="Country" />
        <DxGridDataColumn FieldName="Population" 
                          SortIndex="0" 
                          SortOrder="GridColumnSortOrder.Descending" />
    </Columns>
</DxGrid>

Sort Data at Runtime

You can sort grid data at runtime in the following ways:

  • Use a column’s SortIndex property to specify whether the column takes part in sorting and at which level.
    Note that you need to enclose your code between BeginUpdate and EndUpdate method calls to change values of Grid component parameters outside the Grid component markup. Otherwise, an exception occurs.

    var column = Grid.GetDataColumns().First(i => i.FieldName == "Country");
    Grid.BeginUpdate();
    column.SortIndex = 0;
    column.SortOrder = GridColumnSortOrder.Descending;
    Grid.EndUpdate();
    
  • Call SortBy methods.

    Grid.SortBy("Counrty");
    Grid.SortBy("City", GridColumnSortOrder.Descending);
    Grid.SortBy("CompanyName", GridColumnSortOrder.Descending, 2);
    

Clear Sorting at Runtime

You can clear data sorting in the following ways:

  • Call the ClearSort() method to clear all active sort criteria.
  • Set a column’s SortIndex property to -1 to exclude the column from active sort criteria. Note that you need to enclose your code between BeginUpdate and EndUpdate method calls to change values of Grid component parameters outside the Grid component markup. Otherwise, an exception occurs.
  • Call the SortBy(String, GridColumnSortOrder, Int32) method and pass -1 as the sortIndex parameter to exclude the specified column from active sort criteria.

Note

A grouped column is always sorted. If you clear column sorting, the Grid ungroups the column.

Sort Data by Value or Display Text

The Grid sorts column data by values unless the column editor is a combo box with specified text and value field names. In the latter case, the Grid sorts column data by display text strings.

Set a column’s SortMode property to Value or DisplayText to switch between sort modes.

<DxGridDataColumn FieldName="Country" SortMode="GridColumnSortMode.DisplayText">

Note

The Grid does not support sorting data by display text when you use a Server Mode data source or GridDevExtremeDataSource.

Custom Sorting

The Grid allows you to apply a custom sorting algorithm to column data. Follow the steps below to implement this functionality:

  1. Set a column’s SortMode property to Custom.
  2. Handle the CustomSort event to implement custom sorting logic. The event allows you to compare two rows and specify the comparison result. You can use Value1 and Value2 properties to compare row values in the processed column or call GetRow1Value(String) and GetRow2Value(String) methods to get row values in other columns.
  3. Set the Handled property to true to indicate that the current comparison operation is handled.

Note

The Grid does not support custom sorting when you use a Server Mode data source or GridDevExtremeDataSource.

The following code snippet sorts the Country column by country population.

<DxGrid Data="countryInfo" CustomSort="Grid_CustomSort" >
    <Columns>
        <DxGridDataColumn FieldName="Country" SortMode="GridColumnSortMode.Custom" />
        <DxGridDataColumn FieldName="Population" />
    </Columns>
</DxGrid>

@code {
    CountryInfo[]? countryInfo;
    protected override async Task OnInitializedAsync() {
        countryInfo = await CountryInfo.GetData();
    }
    void Grid_CustomSort(GridCustomSortEventArgs e) {
        if(e.FieldName == "Country") {
            var population1 = (int)e.GetRow1Value("Population");
            var population2 = (int)e.GetRow2Value("Population");
            e.Result = population1.CompareTo(population2);
            e.Handled = true;
        }
    }
}

Blazor Grid Sort Data

Limitations

  1. The Grid has the following limitations when you use a Server Mode data source or GridDevExtremeDataSource:

    • Custom sorting is not supported.
    • Sorting data by display text is not supported.
    • A data sorting operation cancels any “select all” or “deselect all” operation in progress.
  2. Drag and drop operations initiated externally can operate in DropTargetMode.Component mode only.

This section contains a comprehensive sorting-related API reference.

Grid API member Type Description
AllowSort Property Specifies whether users can sort grid data.
ClearSort() Method Clears sorting.
GetSortedColumns() Method Gets the collection of sorted columns.
SortBy Method Sorts data by column values.
CustomSort Event Allows you to implement custom logic used to sort data in the grid.
Column API member Type Description
AllowSort Property Specifies whether users can sort data by the current column.
SortIndex Property Specifies the column’s index among sorted columns. If the property is set to -1, the grid data is not sorted by this column.
SortMode Property Specifies how the Grid sorts column data (by values, by display text, or custom logic is used).
SortOrder Property Specifies the column’s sort order (ascending or descending).
SortIndexChanged Event Fires when the column’s sort index changes.
SortOrderChanged Event Fires when the column’s sort order changes.

Task-Based Examples

This section contains code samples that demonstrate data sorting functionality.

Get Sorted Columns

Call the GetSortedColumns() method to get a collection of sorted columns. Note that grouped columns are always sorted and have the highest sort priority. Therefore, the Grid maintains grouped columns at the beginning of the sorted column collection.

IEnumerable<IGridDataColumn> sortedColumns = Grid.GetSortedColumns();

Sort Groups by Other Column Values

When you group data by a field, the Grid sorts all data by this field as well. You can handle the CustomSort event to implement custom sorting logic for a column.

In the following code snippet, Group column values are sorted according to ImportanceValue field values.

<DxGrid Data="Data" ShowGroupPanel="true" CustomSort="Grid_CustomSort">
    <Columns>
        <DxGridDataColumn FieldName="GroupName" Caption="Group" GroupIndex="0"
                          SortMode="GridColumnSortMode.Custom" />
        <DxGridDataColumn FieldName="Name" SortIndex="1" />
        <DxGridDataColumn FieldName="Value" />
    </Columns>
</DxGrid>

@code {
    object Data { get; set; }

    protected override void OnInitialized() {
        Data = new List<MyData> {
            new MyData { ImportanceValue = 1, GroupName = "High", Name = "Item1", Value = "Value1" },
            new MyData { ImportanceValue = 3, GroupName = "Low", Name = "Item5", Value = "Value5" },
            new MyData { ImportanceValue = 1, GroupName = "High", Name = "Item6", Value = "Value6" },
            new MyData { ImportanceValue = 2, GroupName = "Normal", Name = "Item4", Value = "Value4" },
            new MyData { ImportanceValue = 2, GroupName = "Normal", Name = "Item2", Value = "Value2" },
            new MyData { ImportanceValue = 3, GroupName = "Low", Name = "Item8", Value = "Value8" },
            new MyData { ImportanceValue = 1, GroupName = "High", Name = "Item3", Value = "Value3" },
            new MyData { ImportanceValue = 2, GroupName = "Normal", Name = "Item7", Value = "Value7" }
        };
    }
    void Grid_CustomSort(GridCustomSortEventArgs e) {
        if(e.FieldName == "GroupName") {
            var val1 = (int)e.GetRow1Value("ImportanceValue");
            var val2 = (int)e.GetRow2Value("ImportanceValue");
            e.Result = val1.CompareTo(val2);
            e.Handled = true;
        }
    }
    class MyData {
        public int ImportanceValue { get; set; }
        public string GroupName { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
    }
}

Custom Sorted Groups