C# – Sorting child nodes of a treeview after populating the treeview in c# winforms

csortingtreeviewwinforms

I am having trouble sorting child nodes of a treeview in my winforms program. My treeview is populated by some XML files and it uses an internal text inside the xml files as Text property of nodes (So I think I cant sort them before adding them to the tree view, or if it is possible, since the xml files are big in size I dont want to waste the process). A populated treeview in my program looks like this:

enter image description here

As you can guess I want child nodes to sort like (I dont want HBM\D10 to come after HBM\D1) rather I want:

    HBM\D1
    HBM\D2
    HBM\D3
etc...

I have already tried treeView1.Sort() and also adding beginUpdate and endUpdate but I had no suceess 🙁

I am using .NET 4, any tips would be appriciated

ok I sortet it out using Thomas's advice:

    class NodeSorter : IComparer
{
        public int Compare(object x, object y) 
        {         
            TreeNode tx = (TreeNode)x; 
            TreeNode ty = (TreeNode)y;

            if (tx.Text.Length < ty.Text.Length)
            {
                return -1;
            }

            if (tx.Text.Length > ty.Text.Length)
            {
                return 1;
            }

            return 0;
        } 
}

Best Answer

You need to create a custom comparer and assign it to the TreeViewNodeSorter property:

public class NodeSorter : System.Collections.IComparer
{
    public int Compare(object x, object y)
    {
        TreeNode tx = (TreeNode)x;
        TreeNode ty = (TreeNode)y;

        // Your sorting logic here... return -1 if tx < ty, 1 if tx > ty, 0 otherwise
        ...
    }
}


...

treeView.TreeViewNodeSorter = new NodeSorter();
treeView.Sort();
Related Topic