Moving node up in TreeView

Dec 14 2006 12:08 PM
Dear all,

I'm trying to do a very simple thing: move a node up in a TreeView control.
Now, I need to move the entire node, not just its text, and this is the code I've tried:

            int index = categoriesTree.SelectedNode.Index;
            if (index > 0)
            {
                TreeNode previousNode = categoriesTree.SelectedNode.Parent.Nodes[index - 1];
                categoriesTree.SelectedNode.Parent.Nodes[index - 1] = categoriesTree.SelectedNode.Parent.Nodes[index];
                categoriesTree.SelectedNode.Parent.Nodes[index] = previousNode;
            }

It seems to me that it should work... and it does. But, what happens is that after this method (this code is inside a method, by the way) ends, the TreeView creates another two nodes by itself, as it seems!

Let me show you an example. I have a tree like this:

Root
 |
 \--First Child
      |
      |--First Subchild
      |
      |--Second Subchild
      |
      |--Third Subchild
      |
      \--Fourth Subchild

Now, I select the Fourth Subchild and I execute the method to move it up. All that should happen would be that the Fourth Subchild should change places with the third, but... after the end of the method, the tree looks like this:

Root
 |
 \--First Child
      |
      |--First Subchild
      |
      |--Second Subchild
      |
      |--Fourth Subchild
      |
      |--Third Subchild
      |
      |--Third Subchild
      |
      \--Fourth Subchild


Any ideas of why this is happening and how to solve it?

Thanks!
Felipe Ceotto.

Answers (2)