Sorting an ASP.NET treeview (or a SPTreeview) using an Extension


A very long time ago, I found and used a piece of code that allowed me to extend my Treeview, so that I could sort the nodes. Years have passed since I have had to sort a treeview, and assumed by now it would be a simple search on the internet to find me the code. Unfortunately not. Luckily for me I remembered the very old project that I used the extension in.

The code is below. Please feel free to use it. Also I will know where to find it straight away next time.

using System;
using System.Web.UI.WebControls;
namespace Extensions
{
    public static class Treeview
    {
        public static void Sort(this TreeView tv)
        {
            TreeNodeCollection T = tv.Nodes.Sort();
            tv.Nodes.Clear();
            tv.Nodes.AddRange(T);
        }
        public static void Sort(this TreeNode tn)
        {
            TreeNodeCollection T = tn.ChildNodes.Sort();
            tn.ChildNodes.Clear();
            tn.ChildNodes.AddRange(T);
        }
        public static TreeNodeCollection Sort(this TreeNodeCollection tnc)
        {
            TreeNodeCollection T = new TreeNodeCollection();
            while (tnc.Count > 0)
            {
                string comp = "";
                TreeNode tmp = new TreeNode();
                foreach (TreeNode node in tnc)
                {
                    if (node.Text.CompareTo(comp) > 0)
                    {
                        tmp = node;
                        comp = node.Text;
                    }
                }
                T.AddAt(0, tmp);
                tnc.Remove(tmp);
            }
            foreach (TreeNode sub in T)
            {
                sub.Sort();
            }
            return T;
        }
        public static void AddRange(this TreeNodeCollection TNC, TreeNodeCollection Col)
        {
            foreach (TreeNode node in Col)
            {
                TNC.Add(node);
            }
        }
    }
}

Simply add all your nodes to your Treeview then call

mytreeview.Sort();
Advertisements