2011-05-05 103 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();