Reputation: 933
I have a TreeView
in WinForm application, and I am using the add
, reorder
and delete
methods to add new nodes, reorder existing nodes and delete old notes.
Sometimes when I add a new item it does net show immediately in the TreeView
, but it does show correctly when I add the next node. It seems to happen randomly, so it's difficult to find the root cause.
Even when the node does not show correctly in the UI, the node count 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 the question is not meaningless. 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);
}
}
Upvotes: 4
Views: 1883
Reputation: 186
I think this might be related to the use of Clone, which produces a shallow copy. The node count is update due to the use of the Add method, but the "new" node still has the reference from the one it was created from, so it's not a unique object. Try creating a deep copy instead and see how that goes.
e.g:
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 your desired parent node.
Upvotes: 1
Reputation: 18843
If I am not mistaken isn't there a
TreeView1.BeginUpdate() method that you could use and at the end utilize the
TreeView1.EndUpdate();
Upvotes: 1
Reputation: 1234
First of all, after calling the GetChildren Method, why are you adding the node to the tree anyway? you should only add it to the tree in case its parentID is empty (or null or 0 depending on its type).
In Addition, 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
Upvotes: 1
Reputation: 25810
Have you tried Invalidate()
versus Refresh()
? Refresh only redraws the Client area, while Invalidate redraws the entire control. It's just a shot in the dark... I've never encountered this problem before.
Upvotes: 3