Sorting via Code
- 3 minutes to read
Sorting via Code
Use a column’s TreeListColumn.SortOrder property, to apply sorting to it. To sort the values of the column in ascending order, set the TreeListColumn.SortOrder property to the Ascending value. To sort in descending order, set it to the Descending value.
To remove sorting against a column set its TreeListColumn.SortOrder property to the None value. If the sort settings for all the columns needs to be removed, call the Tree List’s TreeList.ClearSorting method.
The following code shows how to sort data against the Department column in ascending order:
Once the column’s sort order has been changed, the Tree List’s nodes are rearranged and repainted. If sorting by several columns, the nodes will be rearranged as many times as there are columns involved in the sorting. This can be avoided by using the TreeList.BeginSort and TreeList.EndSort methods. The first method prevents the Tree List control from rearranging its nodes as a result of sorting until the second method is called. This allows sorting to be applied against several columns, and the nodes to be rearranged only once, as a result.
The number of sorted columns is returned by the TreeList.SortedColumnCount property. The column’s TreeListColumn.SortIndex property allows the position of the column in the list of sorted columns to be determined. The columns involved in sorting can be accessed using the TreeList.GetSortColumn method.
When the sort settings for a column are changed, the Tree List does the following:
- raises the TreeList.StartSorting event;
- sorts data according to your settings;
- raises the TreeList.EndSorting event.
Example
The following sample code demonstrates how to apply sorting to the Department and Budget columns.
Data is sorted via the TreeListColumn.SortOrder property. To avoid superfluous updates, the code is enclosed with the TreeList.BeginSort and TreeList.EndSort methods.
using DevExpress.XtraTreeList.Columns;
//...
treeList1.BeginSort();
treeList1.Columns["Department"].SortOrder = SortOrder.Ascending;
treeList1.Columns["Budget"].SortOrder = SortOrder.Descending;
treeList1.EndSort();
Example
The following sample code uses the TreeList.GetSortColumn method and the TreeList.SortedColumnCount property to traverse through columns involved in sorting.