views:

26

answers:

2

I have a class, let's call MyClass. In this class, I have a TreeView property let's call myTreeView In my code, I populate the Nodes of this TreeView so I can use it later on. Then, when it's time to actualy use it, I haven't been able to take all the nodes from myClass and put them in a Tree View Control on my form.

I've tried two things:

1.

aTreeView=MyClass.myTreeView

which simply returns nothing (TreeView is empty)

2.

    For Each newNode As TreeNode In MyClass.myTreeView.Nodes
        aTreeView.Nodes.Add(newNode)
    Next

I get the same result here... an empty TreeView

The weird thing is that when debugging, the TreeView in MyClass is well populated with the proper values and in the loop, newNode isn't empty, there's actually something but for some reason it's not showing anything.

Any help would be appreciated,

Thanks

+1  A: 

The first snippet cannot work because aTreeView is a reference to the TreeView that is stored in the form's Controls collection. The assignment just changes the reference, it doesn't change the actual TreeView that the user is looking at.

The second snippet is flawed because a TreeNode has an owner. The TreeView. The code will empty the TreeView in your class. The moved nodes might not be visible because you used the wrong reference, possible the wrong form instance. Be sure to use the one that the user is looking at. You need to use the TreeNode.Clone() method to create a copy of the node.

Hans Passant
Works great... thx I'll add the code
Iggy
A: 

Thanks to Hans Passant's answer, this is how to make it work...

For Each newNode As TreeNode In MyClass.myTreeView.Nodes 
    Dim cloneNode as new TreeNode
    cloneNode=newNode.Clone()
    aTreeView.Nodes.Add(cloneNode) 
Next 
Iggy