Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

ASP.NET TreeView Sort

5.00/5 (4 votes)
11 Sep 2011CPOL 49.7K  
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:


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

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


C#
sort(node);

Here is the recursive function:


C#
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 { }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)