what error in my code?

private void MoveNode(TreeView src, TreeView dest, bool isAll)
{
TreeNode root = null;
foreach(TreeNode n in dest.Nodes)
{
if(Convert.ToInt32(n.Tag) == rootNodeId)
{
root = n;
}
}

if(root != null)
{
if(isAll)
{
foreach(TreeNode n in src.Nodes)
{
if(Convert.ToInt32(n.Tag) != rootNodeId)
{
root.Nodes.Add(n);
src.Nodes.RemoveAt(n.Index);
}
}
}
else
{
src.Nodes.RemoveAt(src.SelectedNode.Index);
root.Nodes.Add(src.SelectedNode);
}
}
}

it always show me the error in runnting time:

System.ArgumentException

that means the treeview contains same value treeNode !

in fact that just only one treeNode contains.




Answer this question

what error in my code?

  • Cyoung342

    root.Nodes.Add(n);
    the exception raised on this line.

    tell me the node of "some name" existsed

    i want move node(s) from a treeview to another.



  • bmcat

    for(int i=0,j= dest.nodes[0].nodes.count;i<j;i++)

    {

    TreeNode t = new TreeNode();

    // more codes

    }

    runnting time j equals 5.but raised exception on i equals 2.



  • msdn3mar

    In your code you are doing something quite risky and generally not advised... modifying the structure of an array while you are iterating through it in a foreach loop...

    Another issue I see is that by dealing with the index’s of the nodes you run into the potential issue of them not lining up... instead, lets deal with the nodes themselves like this:

    private void MoveNode(TreeView src, TreeView dest, bool isAll)

    {

    TreeNode root = null;

    List<TreeNode> nodesToRemove = new List<TreeNode>();

    foreach (TreeNode n in dest.Nodes)

    {

    if (Convert.ToInt32(n.Tag) == rootNodeId)

    {

    root = n;

    }

    }

    if (root != null)

    {

    if (isAll)

    {

    foreach (TreeNode n in src.Nodes)

    {

    if (Convert.ToInt32(n.Tag) != rootNodeId)

    {

    nodesToRemove.Add(n);

    }

    }

    }

    else

    {

    nodesToRemove.Add(src.SelectedNode);

    }

    foreach (TreeNode node in nodesToRemove)

    {

    src.Nodes.Remove(node);

    root.Nodes.Add(node);

    }

    }

    }

    Here the outcome is more inline with what you were trying to do, only here we note the node(s) that needs moving and add it to a list so that once we have determined all of those that need changing we can simply go through and change only them without changing any array's while iterating through them.



  • S Collins

    On what line of your code there is the exception being raised

  • what error in my code?