65.9K
CodeProject is changing. Read more.
Home

ASP.NET TreeView Sort

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Sep 9, 2011

CPOL
viewsIcon

49702

Easy way to sort nodes in a TreeView using a recursive function.

A few days ago, I needed to sort the nodes of a tree view. The solutions that I found over the Internet did not please me, so I decided to write my own. This solution is a simple recursive function that sorts tree nodes in an alphabetic order.

Create your tree view and add your nodes:

TreeView mytree = new TreeView();
//add your nodes here

Then simply call the sort function with the main node as the argument:

sort(node);

Here is the recursive function:

private void sort(TreeNode node)
{
    foreach (TreeNode n in node.ChildNodes)
        sort(n);
    try
    {
        TreeNode temp = null;
        List<TreeNode> childs = new List<TreeNode>();
        while(node.ChildNodes.Count>0)
        {
            foreach (TreeNode n in node.ChildNodes)
                if (temp == null || n.Text[0] < temp.Text[0])
                    temp = n;
            node.ChildNodes.Remove(temp);
            childs.Add(temp);
            temp = null;
        }
        node.ChildNodes.Clear();
        foreach (TreeNode a in childs)
            node.ChildNodes.Add(a);
    }
    catch { }
}