TreeView find and remove child nodes

G

Guest

I have a treeview of removable drives
when I eject a drive I want to refresh the treeview and remove all the child nodes
associated with that ejected Drive Node.

I have attempted code that will delete the items but I keep receiving a "Object reference not set to an instance of an object." When I step through the code I see that it is deleting a node, then it looks for the same node again.

Here is my code

foreach (TreeNode node childnode in clickedNode)
{
childnode.Remove();
}

For Example The nodes "Unzipped", "Folder2", "Unzipped", "Folder2".
It finds "Unzipped" and deletes it, finds "Folder2" and deletes it, then finds "Unzipped", deletes it, then for some reason, it finds "Folder2" again and trys to delete it but its already been deleted. Which is when I receive the error.

I'm not sure why its reading each node twice....and its not even reading them in the order I put them in.


can anyone please help me here
Thanks and Regards
MVB
 
J

Jonathan Holmes

Hi,

Instead of using foreach, which iterates through the nodes from first to
last, and which may not work correctly when combined with removing them, try
a construct like the following:

while (node.FirstNode!=null)
node.FirstNode.Remove();


Jonathan Holmes

MVB said:
I have a treeview of removable drives
when I eject a drive I want to refresh the treeview and remove all the child nodes
associated with that ejected Drive Node.

I have attempted code that will delete the items but I keep receiving a
"Object reference not set to an instance of an object." When I step through
the code I see that it is deleting a node, then it looks for the same node
again.
Here is my code

foreach (TreeNode node childnode in clickedNode)
{
childnode.Remove();
}

For Example The nodes "Unzipped", "Folder2", "Unzipped", "Folder2".
It finds "Unzipped" and deletes it, finds "Folder2" and deletes it, then
finds "Unzipped", deletes it, then for some reason, it finds "Folder2" again
and trys to delete it but its already been deleted. Which is when I receive
the error.
I'm not sure why its reading each node twice....and its not even reading
them in the order I put them in.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top