I want to sort a given TreeView child nodes in alphabetical order.
Suppose my tree View is like this:
firstNode1
- secondNode1
- thirdNode1
- thirdNode2
- thirdNode3 ...
firstNode2
- secondNode1
- thirdNode1
- thirdNode2
- thirdNode3 ...
I want to sort the nodes in secondNodes of every firstNode.
How can I do it? - I have red about Custom Comparer but cant understand how to use it in my case.
For a normal alphabetical sort simply call the built-in sort:
and you are good.
But sometimes this is not good enough. Then you need to write a custom sorter. This is really simple; all it needs to provide is an
int
for the result of<
,==
or>
, i.e. return-1
,0
or1
respectively. Often the built-in comparers will do after massaging the data a bit..Here is an example of a custom sorter. This is a simple class implementing the
IComparer
interface, which has just one method..It prepares the two node texts for my custom comparison before calling the regular string
Compare
method.The preparation inserts a large number of zeroes to pad a trailing number to a constant length.
It is just an example but will sort e.g. the default names from the designer numerically/chronologically.
You call it by assigning it and then calling sort:
Result:
This is a slightly modified version of the MSDN TreeNodeSorter example. Besides the changed logic do note:
IComparer
interface properly. With the advent of generics we usually have ausing System.Collections.Generic;
clause and this will hide the non-genericIComparer
interface, leading to compiler errors, complaining about the missing type arguments.Adding the qualification takes care of that..: