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.
Loading
Felipe CeottoPosted Dec 15, 2006, 7:36 AM
MartinPosted Dec 14, 2006, 12:35 PM
int index = treeView1.SelectedNode.Index;
if (index > 0)
{
TreeNode previousNode = treeView1.SelectedNode.Parent.Nodes[index - 1];
treeView1.SelectedNode.Parent.Nodes.RemoveAt(index - 1);
treeView1.SelectedNode.Parent.Nodes.Insert(index, previousNode);
}
Keep in mind that the code isn't very safe to use, and will easily crash your application, if you don't select a subnode, but I assume you have other checks for that?