I'm working on an application that uses a tree view. The tree view has three type of nodes:
- Root nodes: Those ones can not be sorted, their tag contains the string "Root" to identify them, and the child nodes has this type of node as a parent.
- Folders: Those can be sorted, the idea is that always are before the other nodes on top and sorted in ascending order A->Z. These have the tag "Folders".
- Others: The idea is that those are before folders and also sorted in ascending order A->Z
Here's how this tree view looks:
The idea is to sort all child nodes inside the root nodes (Sounds, Audio Data), and having always the folders before the nodes.
I've been trying with this code but does not work:
// Create a node sorter that implements the IComparer interface.
public class NodeSorter : IComparer
{
public int Compare(object x, object y)
{
int resultComparing;
TreeNode tx = x as TreeNode;
TreeNode ty = y as TreeNode;
if (tx.Tag.ToString().Equals("Root") || ty.Tag.ToString().Equals("Root"))
{
resultComparing = 2;
}
else if (tx.Tag.ToString().Equals("Folder") || ty.Tag.ToString().Equals("Folder"))
{
resultComparing = string.Compare(tx.Tag.ToString(), ty.Tag.ToString(), true);
}
else
{
resultComparing = string.Compare(tx.Text, ty.Text, true);
}
return resultComparing;
}
}
It would also be interesting that the code are very optimized because this tree view can contain easily more than 500 nodes.
Thanks!
The root nodes have no parents and their
Level
properties return0
so you don't need to use theirTag
properties to identify them. You just need to identify theFolder
nodes in the sorter to sort and keep them on top of the other nodes. Then lastly sort the rest.