Reputation: 797
Actually in my treeview ,when i remove a tree node it removes all its child node, But i need to move its child node upwards instead of removing .I have to use in winforms in c sharp.
Anybody help me out.
Upvotes: 2
Views: 6660
Reputation: 4495
You can loop through the child nodes and add them to the node's parent before removing the node itself. This code should handle cases where the node to be removed is a parent node.
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();
Upvotes: 1
Reputation: 19609
The problem you're having is caused by the fact that the child nodes of any given node is stored in myNode.Nodes
. So, when you remove a node all of its nodes are freed as well, so you will have to first iterate through the child nodes, move them, then remove the original node:
//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
Upvotes: 1
Reputation: 1443
What Rhapsody said.
And here is an example:
if (tree.Nodes.Contains(theNode))
{
TreeNodeCollection childNodes = theNode.Nodes;
tree.Nodes.Remove(theNode);
foreach (TreeNode child in childNodes)
{
tree.Nodes.Add(child);
}
}
Upvotes: 2
Reputation: 6077
So you just want to remove a node and keep any childnodes?
What you have to do is:
Upvotes: 4