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