BlaShadow
BlaShadow

Reputation: 11703

Delete all item from a 'TreeView' in .NET 2.0

I got a TreeView with too many elements when I bind it. It's pretty fast because I use beginUpdate and endUpdate, but when I say

treeView.beginUpdate();

treeView.items.clear();

treeView.endUpdate();

it does not take the same efficiency as when I add. When I clear all items, it's taking a long time and does not pause the UI.

Upvotes: 0

Views: 5079

Answers (2)

Darko Kenda
Darko Kenda

Reputation: 4960

If the Nodes collection has more than 200 items, the BeginUpdate() and EndUpdate() methods are called automatically by the Clear() method, which is why you propbably didn't really notice any difference.

This, however, doesn't help you very much since what the Clear() method does is that it walks the entire tree and removes all children, which of course takes a lot of time. Unfortunately the Nodes property is read-only, so you can't just initalize the TreeViewNodeCollection.

Recreating the TreeView control - as Daro suggested - would probably be a viable option as it is really fast, HOWEVER it doesn't appear to release the memory immediately (calling Dispose() of course walks through all the nodes again). I tested it by forcing the garbage collection and it did clean it up, which means that sooner or later it probably would get cleaned up by automatically.

SuspendLayout();
    Controls.Remove(treeView1);
    treeView1 = new TreeView();
    treeView1.Location = new Point(39, 39);
    treeView1.Size = new Size(213, 210);
    Controls.Add(treeView1);
ResumeLayout();

Upvotes: 1

Daro
Daro

Reputation: 2020

Try collapsing the TreeView first (assuming not all nodes are at the top level):

treeView.beginUpdate();
treeView.items.CollapseAll();
treeView.items.clear();
treeView.items.endUpdate();

Upvotes: 0

Related Questions