Michaël Carpentier
Michaël Carpentier

Reputation: 2135

ASP.NET TreeView sort

I am accustomed to winform TreeView having a Sorted property which automatically manages nodes sorting. I now have to alphabetically sort an ASP.NET TreeView and I'm surprised I cannot find any similar property or callback method.

Is there any way to automatically achieve this operation in ASP.NET or do I have to manually sort and insert my nodes in correct order?

Upvotes: 2

Views: 6599

Answers (2)

Kevin Brydon
Kevin Brydon

Reputation: 13112

Three years later and the TreeView still doesn't support sorting natively. Here's a simple method to do sort all nodes alphabetically.

private void SortTreeNodes(TreeNodeCollection treeNodes)
{
    var sorted = true;

    foreach (TreeNode treeNode in treeNodes)
    {
        SortTreeNodes(treeNode.ChildNodes);
    }

    do
    {
        sorted = true;

        for (var i = 0; i < treeNodes.Count - 1; i++)
        {
            var treeNode1 = treeNodes[i];
            var treeNode2 = treeNodes[i + 1];

            if (treeNode1.Text.CompareTo(treeNode2.Text) > 0)
            {
                treeNodes.RemoveAt(i + 1);
                treeNodes.RemoveAt(i);

                treeNodes.AddAt(i, treeNode2);
                treeNodes.AddAt(i + 1, treeNode1);

                sorted = false;
            }
        }
    } while (!sorted);
}

Call it like this

SortTreeNodes(myTreeView.Nodes);

Upvotes: 3

Eoin Campbell
Eoin Campbell

Reputation: 44268

You'll need to write your own sorting function but its reasonably trivial to add this functionality.

http://blog.mdk-photo.com/post/C-Extentionmethod-Tree-Node-View-Sort().aspx

.NET 3.5 supports extension methods so you can add functionality to pre-existing System Classes. Notice the this syntax on the method parameter. More Info Here

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);
} 

The first link contains the rest of the code you'll need to complete the sorting functionality

Upvotes: 4

Related Questions