Is there an easy way to add nodes to a WinForms .NET TreeView control where the new nodes being added are inserted at the correct index so the entire list of nodes is sorted alphabetically? Pretty much having the same result as TreeView.Sort()
.
I have a TreeView that continually grows to a couple hundred nodes. The user can view this TreeView in real time as it grows. I'd prefer to just insert the nodes at the correct index, rather than calling TreeView.Sort() each time after a node is added.
Can this be done?
In winforms, you can simply set the TreeView's
.Sorted
property toTrue
.Ref MSDN
Why don't you create new classes that inherits from
TreeView
andTreeNodeCollection
? The newTreeView
will use your newTreeNodeCollection
and you can override theAdd()
method of theTreeNodeCollection
to do what you're suggesting.The method would have to: 1. Find the correct position to insert into and 2. Insert the new node.
The most trivial implementation would iterate through the collection until
thisNode.value<=newNode.value<nextNode.value
. Then insert beforenextNode.Index
. You could see a performance increase if you use a different search algorithm, depending on the size of the collection. (Something like a binary search comes to mind.)Note: You could also just create an extension method on a
TreeNodeCollection
that does the same thing. However, overriding theAdd()
method ensures yourTreeView
is always sorted. Creating only an extension method may lead to undefined results if it is not already sorted before yourAddIntoSorted()
call.