TreeView Issue RRS feed

  • Question

  • Hi all,

    While building a treeview (C# Forms) I've a display issue. The code is like this:

    IList<TreeNode> listnodescustom = new List<TreeNode>(); for (var i = 0; i < 100; i++) { listnodescustom.Add(new TreeNode() { Name = "Node" + i, Text = "Node" + i }); } TreeNode child = new TreeNode() { Name = "Child", Text = "Child" }; foreach (TreeNode nodecustom in listnodescustom) { nodecustom.Nodes.Add(child); } TreeNode root = new TreeNode() { Name = "Root", Text = "Root" }; root.Nodes.AddRange(listnodescustom.ToArray()); this.treeView1.Nodes.Add(root);

    When the treeview is displayed i've all the child nodes appended to the last element of the list.
    I tried to debug it a bit but in fact everything seems well.

    By example i've setup an anotation on eachnode, and an event onmouseover to show count of child element and name of each child element. for each customnode I get annoatation showing 1 child node only, but the displayed view print them all to last element like the above picture.

    Really I don't understand what I'm doing wrong or if this is a well-known issue.
    I do this because I need to append a common child Treenode to all elements of the list.

    Thanks for your help

    Tuesday, October 8, 2013 12:53 PM


  • Hi Vincent,

    It’s easy to solve this issue, you just need to put the child instance into the foreach statement. Like below:

    foreach (TreeNode nodecustom in listnodescustom)


                    TreeNode child = new TreeNode() { Name = "Child", Text = "Child" };



    I think this may be an error about TreeView class, so I post a feedback to Microsoft Connect to ask for the more efficient workaround. Please vote on it to get a higher degree of concern. https://connect.microsoft.com/VisualStudio/feedback/details/804884/treeview-issue

    Hope useful to you.

    Best Regards,


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, October 9, 2013 3:06 AM
  • Hi Hetro,

    Thanks for your answer. You're right it's working fine.
    I wanted to create child TreeNode first as a reference object for many part in my code because used many times. Probably related to pointer on memory behind and thank I had to duplicate object first.

    Hopefully TreeNode has the Clone() method.

    Therefore I end with this one working to keep my child object already set.

                foreach (TreeNode node in root.Nodes)
                    //node.Nodes.Add(child);   //bug

    Thanks for your answer.


    Friday, October 11, 2013 3:16 PM

All replies