Move treenodes up and down the tree

J

John Rogers

How do you move a selected node up or down a treeview?
Not by drag and drop but by clicking a button to move the
node up or down.

I tried the following, but my tree gets all messed up after I move
the first node.

TreeNode sourceNode = treeView.SelectedNode;

if (sourceNode.Parent == null)
return;


treeView.Nodes.Remove(sourceNode);
treeView.Nodes.Insert(sourceNode.Index + 1, sourceNode);




Thanks



John
 
N

Nicholas Paldino [.NET/C# MVP]

John,

You should get the parent of the parent of the node before you remove
it, and then add the node to the grandparent:

TreeNode sourceNode = treeView.SelectedNode;

if (sourceNode.Parent == null)
{
return;
}

if (sourceNode.Parent.Parent == null)
{
return;
}

sourceNode.Parent.Nodes.Remove(sourceNode);
sourceNode.Parent.Parent.Nodes.Add(sourceNode);
 
J

John Rogers

"Nicholas Paldino [.NET/C# MVP]" <[email protected]>
wrote in message
John,

You should get the parent of the parent of the node before you
remove it, and then add the node to the grandparent:

TreeNode sourceNode = treeView.SelectedNode;


Thanks very much for your help Nicholas.


John
 
J

John Rogers

Nicholas,

I tried the code but it kept erroring out when trying to add the node
without doing
a new Treenode() first. I did a bit of searching to see if there was
any sample
code on how this is done, but I couldn't find anything at all.
Actually I found two
examples but none of them worked, its probably for an older version of
c#.


John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top