13,662,337 members
Tip/Trick
Add your own
alternative version

#### Stats

31.9K views
3 bookmarked
Posted 9 Sep 2011
Licenced CPOL

# ASP.NET TreeView Sort

, 11 Sep 2011
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 { }
}```

## License

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

## About the Author

 Software Developer (Senior) Martifer Inovação e Gestão Portugal
No Biography provided

## Comments and Discussions

 First Prev Next
 incorrect comparison Member 1024692319-Nov-14 3:04 Member 10246923 19-Nov-14 3:04
 compare full words Klimovec12-Apr-12 2:49 Klimovec 12-Apr-12 2:49
 Heyy it worked for me. Currently i have a treeview which pop... rjkumar19879-Jan-12 2:27 rjkumar1987 9-Jan-12 2:27
 Re: just replace the logical comparison "n.Text[0] < temp.Text[0... brunofer200714-Jan-12 23:59 brunofer2007 14-Jan-12 23:59
 1-The datasource should be sort not the tree in asp.net. An... JoePatent13-Sep-11 8:03 JoePatent 13-Sep-11 8:03
 Re: 1 - Sometimes a TreeView doesn't have necessarily a datasour... brunofer200714-Sep-11 0:36 brunofer2007 14-Sep-11 0:36
 Could I ask, why can't you use the default TreeView Sort met... George Swan11-Sep-11 20:11 George Swan 11-Sep-11 20:11
 Re: Hello George, as you can see in the title, this solution is ... brunofer200711-Sep-11 22:21 brunofer2007 11-Sep-11 22:21
 Last Visit: 31-Dec-99 18:00     Last Update: 15-Aug-18 19:01 Refresh 1

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin

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

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180810.1 | Last Updated 11 Sep 2011
Article Copyright 2011 by brunofer2007
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid