通过TreeView.Nodes分配TreeNodeCollection [英] Assign TreeNodeCollection through TreeView.Nodes
本文介绍了通过TreeView.Nodes分配TreeNodeCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经声明了TreeNodeCollection
I have declared a TreeNodeCollection
public TreeNodeCollection NewTreeCollection ;
NewTreeCollection = MyTreeview.Nodes;
现在在
Now in
tabIndexChanged(object sender, EventArgs e) //event
{
//I am storing the NewTreeCollection into a global class object
InterfaceData.tnCollectionNodes = this.NewTreeCollection //InterfaceData is globalclass object
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
this.MyTreeview.Nodes.Clear();
NewTreeCollection正在成为null以及全局类对象
the NewTreeCollection is becomming null as well as the global class object
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
this.MyTreeview.Nodes.Clear();
推荐答案
你需要制作一个< a href =http://msdn.microsoft.com/en-us/library/system.windows.forms.treenodecollection.copyto.aspx> copy [ ^ ]。请记住,当您使用以下内容初始化参考时:
You need to make a copy[^] of the original before clearing it. Remember, when you initialise the reference with:
NewTreeCollection = MyTreeview.Nodes;
NewTreeCollection
只是原始的引用(指针),而不是它的副本。
that NewTreeCollection
is merely a reference (pointer) to the original, not a copy of it.
你是全局类对象只是一个引用您的本地对象。无论您对全局对象执行何种操作,都可以在本地对象上执行(反之亦然)。将您的全局对象视为指向本地对象的指针,而不是对象的副本。
为了做你想做的事,你需要创建一个深度复制树节点集合的方法。 在此处查看解决方案 [ ^ ]。还有其他方法可以使用序列化和内存流,但我认为你应该选择简单的东西。
BTW,C#(.NET)中的所有对象都以相同的方式运行,你传递的是对象引用,而不是整个新对象。
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.
>
这篇关于通过TreeView.Nodes分配TreeNodeCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文