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:
As default, they sorted by name (alphabetically). As you said, the goal is to:
- Sort only Level 0 nodes.
- 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:
Empty folders positioned first. Then - non-empty. Childs not affected.