Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
        } 
}
like image 291
Saeid Yazdani Avatar asked Dec 07 '22 22:12

Saeid Yazdani


2 Answers

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();
like image 192
Thomas Levesque Avatar answered May 19 '23 05:05

Thomas Levesque


You're using alphabetic sorting, so D10 comes after D1.
You should try to sort discarding "D" char and converting the rest of string to a number.

like image 45
Marco Avatar answered May 19 '23 05:05

Marco