Hello everybody,
For the last 2 days im trying to deal with a treeview. What i want to do is to copy the structure from one tree to another. I know there are other ways to do this, but the way i want is to iterate through any node-of any depth-. Im using Telerik's GridView. The code below is the work that i've done so far, but when i run it it throws an Exception saying:"The collection has changed. The iteration may not be executed".

Im first calling the CopyTree() function:

public void CopyTree(RadTreeView trv)
        {
            NodesArr = new ArrayList();
            foreach (RadTreeNode n in trv.Nodes)
            {
                DoTreeWork(n);
            }

            foreach (RadTreeNode node in NodesArr)
            {
                tv2.Nodes.Add(node);
            }
        }

And then the DoTreeWork():

public void DoTreeWork(RadTreeNode node)
{
    RadTreeNode n = node;
    RadTreeNode temp = new RadTreeNode(node.Text);
    temp.Name = node.Name;

    foreach(RadTreeNode child in n.Nodes) ----------> The Exception is thrown.
    {
       temp.Nodes.Add(child);
       DoTreeWork(child);
    }
    tv2.Nodes.Add(temp);
}

I need an helping hand as soon as possible, because i need to continue with my project.

Thanks in advance,

Recommended Answers

All 3 Replies

I think the problem is that you are moving the child node.

public void DoTreeWork(RadTreeNode node)
{
    RadTreeNode n = node;
    RadTreeNode temp = new RadTreeNode(node.Text);
    temp.Name = node.Name;

    foreach(RadTreeNode child in n.Nodes) ----------> The Exception is thrown.
    {
       temp.Nodes.Add(child); //<-- Moving child! Should do copy
       DoTreeWork(child);
    }
    tv2.Nodes.Add(temp);
}

Could you explain this "copy" thing a little bit more? Im kinda dizzy from all the thinking that i've done for this. :p

Thanks in advance,
Alex

The "copy" function is exactly what you are doing.
But you have only done enough to copy the root nodes.
You are very nearly there.

Firstly, because root nodes get bound to the tree view, this first level is perhaps better done in your CopyTree method.

Next, think about how you can modify the DoTreeWork method to take in a parent node from the destination treeview as well as the child node. Then create a new child node and add to the parent.
Call DoTreeWork for each child of the input node (as you do now), passing in appropriate node parameters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.