Treeview does not refresh to show childnode moved from one parent node to another
I am using the Windows Forms TreeView
class which contains a set of TreeNode
s. The TreeNode
s can have child nodes.
I have a root node with 2 sub nodes (Node1 and Node2)
Node1 has 2 subnodes (child1 and child2)
I have a function that will allow a user to select any node and move it to another node:
TreeNode SelectNode = this.TreeView1.SelectedNode;
TreeNode DestNode = SelectedNewNode(); //function to select a new node
SelectedNode.Remove();
DestNode.Nodes.Add(Se开发者_开发百科lectedNode);
this.TreeView1.Refresh();
When this executes, the current selected node (child2) is removed from its current parent (Node1) and added to Node2.
However, the Refresh()
method of the TreeView
control does not show that child2 is under Node2. If I debug it and look at the Nodes
collection in the TreeView
i do see that child2 is under Node2.
Can anyone tell me why the Refresh()
method does not redraw the new parent to child mapping?
Is there a way to tell the TreeView
to redraw with the new mappings?
I don't know if this is just a typo or not, but in the first line you refer to SelectNode
and then you later add something called SelectedNode
. These might be referring to different variables/properties.
Otherwise, there is either a problem with your SelectedNewNode
function, or this code is being executed in some long-running synchronous operation and no repaints are happening at all. You don't need the Refresh
method at all; when you invoke the Remove()
method on a TreeNode
, the display will be updated, and when you Add
it to another parent, it will be updated again. Remove the Refresh
call.
If you are indeed trying to update during a long-running operation, then you need to invoke Invalidate
followed by Update
. However, if this isn't in a loop or blocking call somewhere, that's going to be pointless.
There's one other possibility, which is that you've invoked the TreeView.BeginUpdate
method and forgotten to invoke TreeView.EndUpdate
, which would prevent any updates from being displayed.
Just to test this out, I tested this on a new Windows Form with a TreeView
added two roots (Node0
and Node1
) and one child to each (Node2
and Node3
). The following code successfully updates the display of the TreeView
:
TreeNode nodeToMove = treeView1.Nodes.Find("Node3", true).First();
TreeNode newParent = treeView1.Nodes.Find("Node0", false).First();
nodeToMove.Remove();
newParent.Nodes.Add(nodeToMove);
If none of the above suggestions solve your problem, then start from this working example and look at the difference between the working example and your current code.
精彩评论