Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
1.22/5 (2 votes)
I would like to remove all child nodes except the Root node.

Suppose if my treeview is as follows

Root
|->Child
|-> Child
|->Child

I would like to remove all child and finally i would like to display Root with out child nodes any idea please
Posted
Updated 23-Jul-19 23:09pm

TreeView1.Nodes[0].ChildNodes.RemoveAt(0);
TreeView1.Nodes[0].ChildNodes.RemoveAt(1);
TreeView1.Nodes[0].ChildNodes.RemoveAt(2);


use this for treeview child node position
 
Share this answer
 
Comments
Richard Deeming 13-Sep-18 15:00pm    
Aside from the fact that this question is already solved, your solution is incorrect:

* If there are five or more child nodes, your code will remove nodes 0, 2, and 5, leaving 1, 3, and 6+ unscathed.

* If there are less than five child nodes, your code will throw an exception.
I believe you need to get an instance of the "Root" TreeNode, then Clear its Nodes property.
 
Share this answer
 
C#
foreach(TreeNode node in myTreeview.Nodes)
{
   node.Nodes.Clear;
}


Good luck!
 
Share this answer
 
Comments
demouser743 23-Sep-10 10:39am    
Thanks :)
amiraziz 28-Apr-13 3:09am    
and of course :
Clear(); is correct .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900