实际上在我的树视图中,当我删除一个树节点时,它会删除它的所有子节点,但是我需要将其子节点向上移动而不是移除。我必须在c sharp中使用winforms。
任何人帮助我。
答案 0 :(得分:4)
所以你只想删除一个节点并保留任何子节点?
你要做的是:
答案 1 :(得分:2)
狂想曲说的是什么 这是一个例子:
if (tree.Nodes.Contains(theNode))
{
TreeNodeCollection childNodes = theNode.Nodes;
tree.Nodes.Remove(theNode);
foreach (TreeNode child in childNodes)
{
tree.Nodes.Add(child);
}
}
答案 2 :(得分: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
答案 3 :(得分: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();