其实在我的树视图中,当我删除一个树节点时,它将删除它的所有子节点,但是我需要将其子节点向上移动而不是删除。我必须在c sharp中使用winforms。如何删除树节点并向上移动其节点节点?
有人帮我一把。
其实在我的树视图中,当我删除一个树节点时,它将删除它的所有子节点,但是我需要将其子节点向上移动而不是删除。我必须在c sharp中使用winforms。如何删除树节点并向上移动其节点节点?
有人帮我一把。
Rhapsody说了些什么。
这里有一个例子:
if (tree.Nodes.Contains(theNode))
{
TreeNodeCollection childNodes = theNode.Nodes;
tree.Nodes.Remove(theNode);
foreach (TreeNode child in childNodes)
{
tree.Nodes.Add(child);
}
}
所以你只是想删除一个节点,并保留任何孩子节点?
你所要做的是:
用于在适当位置获取子节点的+1 – stuartd 2011-05-05 13:42:58
你是任何给定节点的子节点存储在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
您可以通过子循环节点并在删除节点之前将它们添加到节点的父节点。此代码应处理要删除的节点是父节点的情况。
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();
是不是将节点添加到列表的末尾而不是父节点的位置? – stuartd 2011-05-05 13:41:55
@Stuart是的,他们被添加在最后。我不知道是否通过“向上移动它的子节点”,他意味着将它们添加到父节点的位置或者将它们移动到树状结构中 – Gabriel 2011-05-05 13:47:42