.Net

Implementing custom sort for a Treeview

The Treeview Sort method applies a simple character sort to the node text. For sophisticated business applications this is often too simple and a custom sort is required in order to sort the nodes based upon the content and not just the character representation.

For example, consider this simple scenario with the following nodes:

  1. First Item
  2. Second Item
  3. Third Item
  4. Fourth Item

Sorting these nodes using a character sort will place them in alphabetical order; First, Fourth, Second, Third.

A custom sort is easy to implement and link to a Treeview control. In this example the Tag property of the Node control is used to store data for sorting the nodes. The NodeSort class is assigned to the TreeViewNodeSorter property before sorting the nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
Public Class Form1
   Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        Dim nodParent As TreeNode
        Dim nodChild As TreeNode

        ' Add four nodes and assign the sequence number to the Tag property
       For intNode As Integer = 1 To 4
            nodParent = TreeView1.Nodes.Add(Choose(intNode, "First Node", "Second Node", "Third Node", "Fourth Node"))
            nodParent.Tag = intNode
        Next

        ' Add a series of dates to the 4th node
       For intAdjust As Integer = 1 To 49 Step 7
            Dim dteNode As Date = DateAdd(DateInterval.Day, intAdjust, Date.Now)
            nodChild = nodParent.Nodes.Add(String.Format("{0:dd MMM yy}", dteNode))
            nodChild.Tag = dteNode
        Next

        ' Assign the custom sort class and sort the TreeView
       With TreeView1
            .TreeViewNodeSorter = New NodeSorter
            .Sort()
        End With
    End Sub
End Class

Public Class NodeSorter
    Implements IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) _
        As Integer Implements IComparer.Compare
        Dim tx As TreeNode = CType(x, TreeNode)
        Dim ty As TreeNode = CType(y, TreeNode)

        If TypeOf tx.Tag Is Integer And TypeOf ty.Tag Is Integer Then
            ' Sort numbers in ascending sequence
           Return String.Compare(tx.Tag.ToString, ty.Tag.ToString)
        ElseIf TypeOf tx.Tag Is Date And TypeOf ty.Tag Is Date Then
            ' Sort dates in descending sequence
           Return String.Compare(String.Format("{0:yyyymmdd}", CDate(ty.Tag)), String.Format("{0:yyyymmdd}", CDate(tx.Tag)))
        Else
            ' Sort everything else alphabetically in ascending sequence
           Return String.Compare(tx.Text, ty.Text)
        End If

    End Function
End Class

Note that the dates are sorted in descending sequence simply by swapping the X and Y nodes and comparing Y with X instead of X with Y.