Clearing TreeView taking too much time
Explores an odd feature of the System.Windows.Forms.TreeView and a
simple workaround.
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
|