12,074,449 members (60,055 online)
Tip/Trick
alternative version

23.8K views
3 bookmarked
Posted

# ASP.NET TreeView Sort

, 11 Sep 2011 CPOL
 Rate this:
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.

```TreeView mytree = new TreeView();

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);
temp = null;
}
node.ChildNodes.Clear();
foreach (TreeNode a in childs)
}
catch { }
}```

## Share

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

## You may also be interested in...

 First Prev Next
 incorrect comparison Member 1024692319-Nov-14 4:04 Member 10246923 19-Nov-14 4:04
 compare full words Klimovec12-Apr-12 3:49 Klimovec 12-Apr-12 3:49
 More powerfull staff by me 1) use TreeNodeCollection 2) compare full words private void sort(TreeNodeCollection nodes) { foreach (TreeNode n in nodes) sort(n.ChildNodes); try { TreeNode temp = null; List childs = new List(); while (nodes.Count > 0) { foreach (TreeNode n in nodes) if (temp == null || String.Compare(n.Text, temp.Text,true) < 0) temp = n; nodes.Remove(temp); childs.Add(temp); temp = null; } nodes.Clear(); foreach (TreeNode a in childs) nodes.Add(a); } catch { }; }
 Heyy it worked for me. Currently i have a treeview which pop... rjkumar19879-Jan-12 3:27 rjkumar1987 9-Jan-12 3:27
 Re: just replace the logical comparison "n.Text[0] < temp.Text[0... brunofer200715-Jan-12 0:59 brunofer2007 15-Jan-12 0:59
 1-The datasource should be sort not the tree in asp.net. An... JoePatent13-Sep-11 9:03 JoePatent 13-Sep-11 9:03
 Re: 1 - Sometimes a TreeView doesn't have necessarily a datasour... brunofer200714-Sep-11 1:36 brunofer2007 14-Sep-11 1:36
 Could I ask, why can't you use the default TreeView Sort met... George Swan11-Sep-11 21:11 George Swan 11-Sep-11 21:11
 Re: Hello George, as you can see in the title, this solution is ... brunofer200711-Sep-11 23:21 brunofer2007 11-Sep-11 23:21
 Last Visit: 31-Dec-99 19:00     Last Update: 11-Feb-16 4:14 Refresh 1