Clearing TreeView taking too much time

Recently I'd been working on an application that manipulates a large amount of hierarchical data in a TreeView. One of the application's menu commands (let's call it Clear) caused the TreeView to be cleared and repopulated again. Sometimes, the Clear command was executed in an instant. Sometimes, however, the Clear command took eternity.

After analyzing the problem, I've realized that the Clear command is slowest when the bottommost node in the TreeView is selected. That is, when one invokes the TreeView.Nodes.Clear method while a node in the TreeView is selected, the TreeView seems to be selecting all the nodes as they are being removed. Because node selection generates the AfterSelect event and because the event handler does quite a bit of work (lasting from 200 up to 800 milliseconds on a test machine), the Clear seemed to last forever.

Imagine for example a tree with 1000 nodes with the last node selected. Should the AfterSelect take only 100 milliseconds, the Clear would take almost 100 seconds!

Its odd, but the TreeView does work that way. If you don't believe me, have a look at this code that demonstrates the behavior.

If you do believe me, then please remember: the next time when you'll wonder why TreeView.Nodes.Clear call takes so much time, just replace the call with the following SmartClearNodes call:

Public Shared Sub SmartClearNodes(ByVal tree As TreeView)
  tree.BeginUpdate()
  Try
    tree.SelectedNode = Nothing ' this is it ;-)
    tree.Nodes.Clear()
  Finally
    tree.EndUpdate()
  End Try
End Sub

You might also like...

Comments

Palo Mraz I live in Slovakia with my wife, two sons (fulltime), one daughter (occasionally) and a dog. I've been doing Microsoft Windows development since 1988; primarily in VB. I'm a big fan of the MS .NET ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“To iterate is human, to recurse divine” - L. Peter Deutsch