Back to Devexpress

How to: Sort Nodes Using Custom Rules

aspnet-4338-components-tree-list-examples-how-to-sort-nodes-using-custom-rules.md

latest1.8 KB
Original Source

How to: Sort Nodes Using Custom Rules

  • Dec 17, 2020

The following code shows how to implement custom node sorting by handling the ASPxTreeList.CustomNodeSort event. The “DEPARTMENT” column displays text values. When sorting is applied to this column, the nodes are compared by the length of the “DEPARTMENT” column’s values rather than by the text itself.

The image below shows the result:

csharp
using System.Collections;

protected void ASPxTreeList1_CustomNodeSort(object sender,
DevExpress.Web.ASPxTreeList.TreeListCustomNodeSortEventArgs e) {
    if (e.Column.FieldName != "DEPARTMENT") return;
    e.Handled = true;
    string value1 = e.Node1["DEPARTMENT"].ToString();
    string value2 = e.Node2["DEPARTMENT"].ToString();
    if (value1.Length > value2.Length)
        e.Result = 1;
    else
        if (value1.Length == value2.Length)
            e.Result = Comparer.Default.Compare(value1, value2);
        else
            e.Result = -1;
}
vb
Imports System.Collections

Protected Sub ASPxTreeList1_CustomNodeSort(ByVal sender As Object,_
ByVal e As DevExpress.Web.ASPxTreeList.TreeListCustomNodeSortEventArgs)
        If e.Column.FieldName <> "DEPARTMENT" Then
            Return
        End If
        e.Handled = True
        Dim value1 As String = e.Node1("DEPARTMENT").ToString()
        Dim value2 As String = e.Node2("DEPARTMENT").ToString()
        If value1.Length > value2.Length Then
            e.Result = 1
        Else
            If value1.Length = value2.Length Then
                e.Result = Comparer.Default.Compare(value1, value2)
            Else
                e.Result = -1
            End If
        End If
End Sub