TreeView does not accidentally show newly added nodes

I have a TreeView application in WinForm, and I use the add , reorder and delete methods to add new nodes, reorder existing nodes, and delete old notes.

Sometimes, when I add a new element, it shows net show directly in the TreeView , but it correctly shows when I add the next node. It seems to be happening by chance, so it's hard to find the root cause.

Even if the node does not display correctly in the user interface, the node counter is correct.

 TreeView1.BeginUpdate(); TreeView1.Nodes.Add("P1", "Parent"); foreach(User u in items) { if( condition) { node.Text =u.sNodeText; node.Tag = u; node.Text = u.sNodeText; GetChildren(node); TreeView1.Nodes["P1"].Nodes.Add((TreeNode)node.Clone()); } } TreeView1.ExpandAll(); TreeView1.EndUpdate(); TreeView1.Refresh(); 

Can anyone answer this question? I think this question does not make sense. Here is the GetChildren method.

  private void GetChildren(TreeNode node) { TreeNode Node = null; User nodeCat = (User)node.Tag; foreach (User cat in items) { if (cat.sParentID == nodeCat.sID) { Node = node.Nodes.Add(cat.sNodeText); Node.Tag = cat; GetChildren(Node); } } 
+4
source share
4 answers

Have you tried Invalidate() vs Refresh() ? The update only redraws the client area, while Invalidate redraws the entire control. It’s just a shot in the dark ... I have never encountered this problem before.

+3
source

First of all, after calling the GetChildren method, why are you adding node to the tree anyway? you should only add it to the tree if its parentID is empty (either null or 0 depending on its type). Also, add the EnsureVisible method to your newly added node and remove the cloning:

 ... if (u.sParentID==null) { TreeView1.Nodes["P1"].Nodes.Add(node); node.EnsureVisible(); } ... 

Hope this helps

+1
source

If I am not mistaken, does not exist

 TreeView1.BeginUpdate() method that you could use and at the end utilize the TreeView1.EndUpdate(); 
+1
source

I think this could be due to the use of Clone, which creates a shallow copy . The node counter is updated due to the use of the Add method, but the β€œnew” node still has a link from the one from which it was created, so it is not a unique object. Try creating a deep copy and see how this happens.

eg:

 public TreeNode DeepNodeClone(TreeNode src) { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, src); ms.Position = 0; object obj = bf.Deserialize(ms); ms.Close(); return (TreeNode)obj; } 

Then add this node as a child to the desired parent node.

+1
source

All Articles