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
intfor the result of<,==or>, i.e. return-1,0or1respectively. 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
IComparerinterface, which has just one method..It prepares the two node texts for my custom comparison before calling the regular string
Comparemethod.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:
IComparerinterface properly. With the advent of generics we usually have ausing System.Collections.Generic;clause and this will hide the non-genericIComparerinterface, leading to compiler errors, complaining about the missing type arguments.Adding the qualification takes care of that..: