2011-05-05 104 views

回答

2

Rhapsody说了些什么。
这里有一个例子:

if (tree.Nodes.Contains(theNode)) 
     { 
      TreeNodeCollection childNodes = theNode.Nodes; 
      tree.Nodes.Remove(theNode); 
      foreach (TreeNode child in childNodes) 
      { 
       tree.Nodes.Add(child); 
      } 
     } 
+0

是不是将节点添加到列表的末尾而不是父节点的位置? – stuartd 2011-05-05 13:41:55

+0

@Stuart是的,他们被添加在最后。我不知道是否通过“向上移动它的子节点”,他意味着将它们添加到父节点的位置或者将它们移动到树状结构中 – Gabriel 2011-05-05 13:47:42

4

所以你只是想删除一个节点,并保留任何孩子节点?

你所要做的是:

  1. 从要删除的节点中删除的childNodes。
  2. 在要删除的节点之前添加子节点。
  3. 删除选定的节点。
+0

用于在适当位置获取子节点的+1 – stuartd 2011-05-05 13:42:58

1

你是任何给定节点的子节点存储在myNode.Nodes造成的事实遇到的问题。所以,当你删除它的所有节点都被释放,以及一个节点,所以你必须先经过子节点迭代,移动它们,然后删除原始节点:

//assume treeChild is what you are removing, and treeControl is you TreeView 
//this code will move all of its children nodes 
//to be children of its parent before being removed 

//set that we are updating the treeview control 
//increases performance by blocking the paint methods until update is finished 
treeControl.BeginUpdate(); 

//this will loop through child nodes of what we are removing 
//then add them to the parent 
foreach(TreeView node in treeChild.ChildNodes) 
{ 
    node.Parent.Nodes.Add(node); 
} 

//then remove the node 
treeChild.Remove(); 

treeControl.EndUpdate(); //note that we finished updated the controls 
1

您可以通过子循环节点并在删除节点之前将它们添加到节点的父节点。此代码应处理要删除的节点是父节点的情况。

if (nodeToRemove.Nodes.Count > 0) { 
List<TreeNode> childNodes = new List<TreeNode>(); 
foreach (TreeNode n in nodeToRemove.Nodes) { 
    childNodes.Add(n); 
} 
if ((nodeToRemove.Parent != null)) { 
    nodeToRemove.Parent.Nodes.AddRange(childNodes.ToArray()); 
    } else { 
    nodeToRemove.TreeView.Nodes.AddRange(childNodes.ToArray()); 
    } 
    } 
nodeToRemove.Remove();