Home > OS >  How to sort the nodes of Treeview where the nodes level property is 0 in .Net Winforms
How to sort the nodes of Treeview where the nodes level property is 0 in .Net Winforms

Time:10-14

How to sort the nodes of Treeview where the nodes level property is 0 in .Net Winforms. if there are child nodes available in for a level 0 nodes that should not be sorted.

CodePudding user response:

Don't know what is expected result, but...

I create an example with 6 Folders: 4 empty and 2 non-empty:

enter image description here

As default, they sorted by name (alphabetically). As you said, the goal is to:

  1. Sort only Level 0 nodes.
  2. Do not sort Level 0 node if it has child nodes.

Because you didn't provide a way you want to sort Level 0 nodes, I choose to sort by "Empty folders first, then non-empty". So I create custom sorter called Level0NodeSorter, which positions first Level 0 nodes without childs, then with them:

Public Class Level0NodeSorter
    Implements System.Collections.IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer
        Dim node As System.Windows.Forms.TreeNode = TryCast(x, System.Windows.Forms.TreeNode)
        Return If(node.Level = 0 AndAlso node.Nodes.Count > 0, 1, 0)
    End Function
End Class

Then applied custom sorter to my TreeView:

treeView1.TreeViewNodeSorter = New Level0NodeSorter()
treeView1.Sort()

And get this:

enter image description here

Empty folders positioned first. Then - non-empty. Childs not affected.

  • Related