Back to Devexpress

How to: Implement custom sorting

windowsforms-5619-controls-and-libraries-tree-list-examples-sorting-how-to-implement-custom-sorting.md

latest1.7 KB
Original Source

How to: Implement custom sorting

  • Nov 13, 2018

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.

csharp
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;

}
vb
Imports DevExpress.XtraTreeList

Private treeList1.Columns("Department").SortMode = DevExpress.XtraGrid.ColumnSortMode.Custom

Private Sub TreeList1_CustomColumnSort(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.CustomColumnSortEventArgs)
    If e.Node1.HasChildren AndAlso (Not e.Node2.HasChildren) Then
        e.Result = If(e.SortOrder = SortOrder.Ascending, -1, 1)
    End If
    If (Not e.Node1.HasChildren) AndAlso e.Node2.HasChildren Then
        e.Result = If(e.SortOrder = SortOrder.Ascending, 1, -1)
    End If

End Sub