.net – Sort TreeView Automatically Upon Adding Nodes

netsortingtreeviewwinforms

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?

Best Answer

In winforms, you can simply set the TreeView's .Sorted property to True.

When Sorted is set to true, the TreeNode objects are sorted in alphabetical order by their Text property values. You should always use BeginUpdate and EndUpdate to maintain performance when adding a large quantity of items to a sorted TreeView. When the text of an existing node is changed, you must call Sort to resort the items.

Ref MSDN