Sorting in Code
- 2 minutes to read
Note
Sorting by display text and custom sorting are not supported in Server Mode.
Sorting
The following methods and properties can be used to sort data:
A column’s ColumnBase.SortOrder property specifies the column’s sort order. Set it to ColumnSortOrder.Ascending or ColumnSortOrder.Descending.
<dxg:GridColumn FieldName="ProductName" SortOrder="Ascending"/>
grid.Columns["ProductName"].SortOrder = ColumnSortOrder.Ascending;
- Set a column’s ColumnBase.SortIndex property to a non-negative value. This automatically sorts its values in ascending order.
Specify the DataControlBase.DefaultSorting property. The GridControl sorts its data by the values of the specified column in ascending order. Use the ColumnBase.SortOrder property to specify the sort order:
<dxg:GridControl ... DefaultSorting="ProductName"> <dxg:GridColumn FieldName="ProductName" SortOrder="Descending"/> <!-- ... --> </dxg:GridControl>
Use the grid’s GridControl.SortBy method.
Create a new instance of the GridSortInfo class, specify its GridSortInfo.FieldName and GridSortInfo.SortOrder properties, and add it to the grid’s GridControl.SortInfo collection.
<dxg:GridControl.SortInfo> <dxg:GridSortInfo FieldName="ProductName" SortOrder="Ascending"/> </dxg:GridControl.SortInfo>
GridSortInfo sortInfo = new GridSortInfo("ProductName", System.ComponentModel.ListSortDirection.Ascending); grid.SortInfo.Add(sortInfo);
Unsorting
To unsort data by the values of a single column, do one of the following:
- Set the column’s ColumnBase.SortOrder property to ColumnSortOrder.None.
- Set the column’s ColumnBase.SortIndex property to -1.
Use the grid’s GridControl.SortBy method:
grid.SortBy(grid.Columns["ProductName"], ColumnSortOrder.None);
Remove the corresponding GridSortInfo object from the GridControl.SortInfo collection.
grid.SortInfo.Remove(grid.SortInfo["ProductName"]);
To clear the sorting applied to the grid, use the DataControlBase.ClearSorting method.
Note
If grouping is applied, the DataControlBase.ClearSorting method preserves sorting applied to grouping columns, because group rows are always sorted.
Sorting Events
When sorting data, the grid does the following:
- Raises the GridControl.StartSorting event.
- Sorts data.
- Raises the GridControl.EndSorting event.
Note
Group rows are always sorted. The StartSorting and EndSorting events are also raised before and after data is grouped.