ASP.NET Core 5 | DataGrid Sorting


ASP.NET Core 5 DataGrid Sorting

This is Part 9 of Web development with Blazor series. In this video, we will discuss how to perform sorting in Blazor DataGrid. We discussed paging in our previous video. Click here for the complete course page.

We are using Syncfusion DataGrid component and it's free to use. Click here to claim the free license.

Enable Sorting in Blazor DataGrid

  • To enable sorting simply set AllowSorting property to true.
  • To sort by a specific column, simply click on the column header. 
  • By default, the sorting order will be as Ascending | Descending | None.
  • First click on a column header sorts it in the ascending order. Second click sorts it in the descending order and the third click clears the sorting.
  • Use GridSortSettings component to customise sorting options. 
  • Set AllowUnsort="false" on GridSortSettings if you want to disable clearing the sort on the third click.
  • To disable sorting for a particular column, set AllowSorting property of that GridColumn to false.
<SfGrid DataSource="@Employees" AllowSorting="true">
    <GridColumns>
        <GridColumn Field=@nameof(Employee.EmployeeId) HeaderText="ID"></GridColumn>
        <GridColumn Field=@nameof(Employee.FirstName) HeaderText="First Name"></GridColumn>
        <GridColumn Field=@nameof(Employee.LastName) HeaderText=" Last Name"></GridColumn>
        <GridColumn Field=@nameof(Employee.Email) HeaderText="Email"></GridColumn>
    </GridColumns>
</SfGrid>

Blazor DataGrid Initial Sort Order

For example to have the data sorted by Employee ID column in the descending order when the DataGrid initially loads, use GridSortSettings as in the example below.

<SfGrid DataSource="@Employees" AllowSorting="true" AllowPaging="true">
    <GridSortSettings>
        <GridSortColumns>
            <GridSortColumn Field="EmployeeId" Direction="SortDirection.Descending">
            </GridSortColumn>
        </GridSortColumns>
    </GridSortSettings>
    <GridColumns>
        <GridColumn Field=@nameof(Employee.EmployeeId) HeaderText="ID"></GridColumn>
        <GridColumn Field=@nameof(Employee.FirstName) HeaderText="First Name"></GridColumn>
        <GridColumn Field=@nameof(Employee.LastName) HeaderText=" Last Name"></GridColumn>
        <GridColumn Field=@nameof(Employee.Email) HeaderText="Email" AllowSorting="false"></GridColumn>
    </GridColumns>
</SfGrid>

Multi-column sorting

  • Hold the CTRL key and then click the column header to sort by multiple columns.
  • The sorting order of the columns is displayed in the DataGrid header.
  • To clear sorting for a specific column, press the "Shift + mouse left click".
  • By default, multi-column sorting is turned ON. To turn it off set AllowMultiSorting property to false.




© 2020 Pragimtech. All Rights Reserved.