Click here to Skip to main content
15,880,796 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET TreeView Sort

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
11 Sep 2011CPOL 47.7K   3   8
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)


Written By
Software Developer (Senior) Martifer Inovação e Gestão
Portugal Portugal
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionincorrect comparison Pin
Member 1024692319-Nov-14 3:04
Member 1024692319-Nov-14 3:04 
Suggestioncompare full words Pin
Klimovec12-Apr-12 2:49
Klimovec12-Apr-12 2:49 
GeneralHeyy it worked for me. Currently i have a treeview which pop... Pin
rjkumar19879-Jan-12 2:27
rjkumar19879-Jan-12 2:27 
GeneralRe: just replace the logical comparison "n.Text[0] < temp.Text[0... Pin
brunofer200714-Jan-12 23:59
brunofer200714-Jan-12 23:59 
General1-The datasource should be sort not the tree in asp.net. An... Pin
JoePatent13-Sep-11 8:03
JoePatent13-Sep-11 8:03 
GeneralRe: 1 - Sometimes a TreeView doesn't have necessarily a datasour... Pin
brunofer200714-Sep-11 0:36
brunofer200714-Sep-11 0:36 
1 - Sometimes a TreeView doesn't have necessarily a datasource. The nodes could be added manually (that was my case).


2 - If you watch carefully the code, you see that recursive function it's only called when a node has childnodes:

foreach (TreeNode n in node.ChildNodes)
sort(n);

the recursive function is called as many child nodes you have, so you can predict the number of iterations


3 - I'll explain this step to you:

- temp variable is initialized to null.

- for each child node: if the temp is null, temp = childnode.
if temp != null,
if the first character of childNode < fisrt character of Temp, temp = childNode

- when you reach the end of for each statment, the Temp variable has the lowest start character node.

- add that node to List "childs", this way the list will be filled alphabetically.

- delete temp node from child node.

- start all over again (the temp variable is set to null to store again the lowest start letter node).

- this cycle stops when there are no more childnodes:
while(node.ChildNodes.Count>0)

- then, you simply add again the childnode in the node (alphabetically sorted):
foreach (TreeNode a in childs)
node.ChildNodes.Add(a);


4 - and finally, as I mention before, the sort() method for TreeView is not present on WebForms (ASP.NET).
GeneralCould I ask, why can't you use the default TreeView Sort met... Pin
George Swan11-Sep-11 20:11
mveGeorge Swan11-Sep-11 20:11 
GeneralRe: Hello George, as you can see in the title, this solution is ... Pin
brunofer200711-Sep-11 22:21
brunofer200711-Sep-11 22:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.