5 Ocak 2010 Salı

Removing nodes from .NET TreeViews...

Unfortunetely its complicated to remove a node from a treeview in .NET. After a long time I solved this problem;

If you want to remove the selected node and
  • if the selected node has got a parent, remove it like that:  TreeView1.SelectedNode.Parent.ChildNodes.Remove(TreeView1.SelectedNode);
  • else if the selected node has not got a parent, remove it like that: TreeView1.Nodes.Remove(TreeView1.SelectedNode);
 
In same way, if you want to remove all the child nodes of the selected node, remove the child nodes like that;

int cnt = TreeView1.SelectedNode.ChildNodes.Count;
for (int i = cnt - 1; i >= 0; i--)
 {
     TreeNode myChild = TreeView1.SelectedNode.ChildNodes[i];
     TreeNode myParent =TreeView1.SelectedNode.ChildNodes[i].Parent;                        
      myParent.ChildNodes.Remove(myChild);
 }


Yours sincerely...

Hiç yorum yok:

Yorum Gönder