Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove all child nodes from treeview

Status
Not open for further replies.

hexOffender

Programmer
Nov 6, 2006
146
0
0
US
This should be easy, but I cant find any examples of how to go remove all the child nodes of a Treeview.

This is what I started



Dim nodes As TreeNodeCollection
nodes = TreeView1.Nodes
Dim tn As TreeNode
For Each tn In nodes

tn.Remove()

End If
Next

 
Your code as-is will remove ALL nodes, not just child nodes. Try this:

For Each t As TreeNode In TreeView1.Nodes 'loop through parent nodes
For Each c As TreeNode In t.Nodes 'loop through child nodes
c.Remove() 'remove child node
Next
Next



I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
I am actually trying to remove the second level child nodes (d.nodes), but the code below will not work, it gives me an "Object not set to an instance of an object error". I tried initializing c and d but it did not help.


For Each t As TreeNode InTreeView1.Nodes
For Each c As TreeNode In t.Nodes
For Each d As TreeNode In c.Nodes
d.Remove() '"Object not set..."
Next
Next
Next

Seems like this should work though..
 
I've been debugging this bit of code, and it actually does remove the Child nodes, byt it throws an exception on a node that has 5 child nodes. I have no idea why it would suddenly lose the object reference that it had before, when working under the same node..
 
Surely this is easier ?
Code:
For Each t As TreeNode In TreeView1.Nodes

    t.Nodes.Clear()

Next
 
Actually thats what I ended up doing and then just recreating the treeview.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top