Click here to Skip to main content
15,868,004 members
Please Sign up or sign in to vote.
1.18/5 (3 votes)
See more:
I have declared a TreeNodeCollection
C#
public TreeNodeCollection NewTreeCollection ;
NewTreeCollection = MyTreeview.Nodes;

Now in
C#
tabIndexChanged(object sender, EventArgs e) //event
{
//I am storing the NewTreeCollection into a global class object
InterfaceData.tnCollectionNodes = this.NewTreeCollection //InterfaceData is globalclass object

C#
for (int i= 0; i< InterfaceData.Items.Count<object>(); i++)
{
if ((InterfaceData.Items[i])).PCNames.Equals(tabControl.SelectedTab.Text))
     {
       if (InterfaceData.Items[i].tnCollectionNodes.Count > 0)
           {
             this.MyTreeview.Nodes.Clear();
             this.MyTreeview.Nodes.Add(InterfaceData.Items[i].tnCollectionNodes[0]);
                                    break;
           }
     }
else
     {
       this.MyTreeview.Nodes.Clear();
     }
}

Here the problem comes, when I am doing
C#
this.MyTreeview.Nodes.Clear(); 

the NewTreeCollection is becomming null as well as the global class object
C#
InterfaceDetails.Items[i] is also becomming null.


Can u please help me how i can store the data in the global class so that the global class does not become null after
C#
this.MyTreeview.Nodes.Clear();
Posted
Updated 3-Jul-13 5:38am
v4

You need to make a copy[^] of the original before clearing it. Remember, when you initialise the reference with:
C#
NewTreeCollection = MyTreeview.Nodes;

that NewTreeCollection is merely a reference (pointer) to the original, not a copy of it.
 
Share this answer
 
You're "global" class object is just a reference to your local object. Whatever operations you perform on your global object, also get performed on your local object (and vice-versa). Think of your global object as a pointer to your local object, not a copy of the object.

In order to do what you are wanting, you need to create a method to "deep copy" the tree node collection. Look at the solution here[^]. There are other ways to do it, using serialization and memory streams, but I think you should opt for something simple.

BTW, all objects in C# (.NET) act the same way, you are passing around object references, not entire new objects.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900