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:
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;
}
}
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With