Treeview parent sort

Hi everybody.
I need to sort a treeview, but I must keep intact the child structure. Any idea about strategy

Example:

BEFORE SORT:

root
|
---parent2
|         |---childX
|         |---childA
|
---parent3
|         |---childX
|         |---childA
|
---parent1
         |---childX
         |---childA

AFTER SORT:

root
|
---parent1
|         |---childX
|         |---childA
|
---parent2
|         |---childX
|         |---childA
|
---parent3
         |---childX
         |---childA

Thank you very much for your help



Answer this question

Treeview parent sort

  • C#2.0

    Hi,

    I just coded this up in Visual Studio 2005 and I have not tested it much but this seems to work (you need to add code to guard against nodes with the same text):

    Dim sortedNodes As New SortedDictionary(Of String, TreeNode)
    For Each node As TreeNode In Me.TreeView1.Nodes
        sortedNodes.Add(node.Text, node)
    Next
    Me.TreeView1.Nodes.Clear()
    For Each node As TreeNode In sortedNodes.Values
       
    Me.TreeView1.Nodes.Add(node)
    Next

    TreeView has a Sort method if you provide a TreeViewNodeSorter (http://msdn2.microsoft.com/en-us/library/system.windows.forms.treeview.treeviewnodesorter) but this will sort all the nodes in the TreeView.

    Best regards,



  • Treeview parent sort