Custom Sorting
- 3 minutes to read
Custom Sorting
The Tree List control allows custom sorting algorithms to be implemented for individual columns. These sorting procedures are invoked when data is sorted against specific columns by end-users, or via the TreeListColumn.SortOrder property.
To enable the use of a custom sorting procedure for a column, set the column’s TreeListColumn.SortMode property to Custom. To implement custom sorting logic, handle the TreeList.CustomColumnSort event. When sorting is applied to this column, this event fires each time two node values in the column must be compared.
The result of the node value comparison is specified by the sign of the event’s Result parameter. If it is negative, the first compared value is considered to be the smaller value. If it is positive, the first compared value is considered to be the larger value. Setting Result to 0 specifies that the nodes have identical values. Initially, this parameter contains a value specified by the default sorting algorithm.
Example
The code below implements a custom sorting algorithm for a Tree List column via the TreeList.CustomColumnSort event. The sorting procedure arranges nodes that have children above the nodes that do not have children.
The images below display the control sorted by the Department column in ascending and descending order. Notice that the Finance node is always located under nodes that have children.
using DevExpress.XtraTreeList;
treeList1.Columns["Department"].SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom;
private void TreeList1_CustomColumnSort(object sender, DevExpress.XtraTreeList.CustomColumnSortEventArgs e) {
if (e.Node1.HasChildren && !e.Node2.HasChildren)
e.Result = e.SortOrder == SortOrder.Ascending ? -1 : 1;
if (!e.Node1.HasChildren && e.Node2.HasChildren)
e.Result = e.SortOrder == SortOrder.Ascending ? 1 : -1;
}
Example
Custom sorting can be used if you wish to sort string values as numbers. Assume that the values “2” and “10” exist within a column. If standard sorting is used, “10” will be considered to be less than “2”, so write the following TreeList.CustomColumnSort event handler to avoid this behavior.
treeList1.Columns["Budget"].SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom;
private void TreeList1_CustomColumnSort(object sender, DevExpress.XtraTreeList.CustomColumnSortEventArgs e) {
if (e.Column.Caption != "Budget") return;
try {
int value1 = Convert.ToInt32(e.NodeValue1);
int value2 = Convert.ToInt32(e.NodeValue2);
e.Result = value1 - value2;
}
catch { }
}
Sorting string values as numbers is not the only reason to implement custom sorting. You can also use this feature if you want sorting to be dependent upon the properties of nodes, or upon the data in other columns.