Swapping nodes in TreeView

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using a TreeView to display the hierarchy of a strongly-typed collection
(inherited from CollectionBase). The order of the nodes in the TreeView is
strictly tied to the order in which they appear in the underlying collection.
However, the user must be able to reorder certain items in the
collection--and, hence, the TreeView.

I have created a context-sensitive menu that allows the user to move an item
in the collection either up or down. To move the items in the collection up
or down, I have written a Swap() method that easily accomplishes this.
However, swapping the associated TreeNode nodes in the TreeView is turning
out to be problematic. There doesn't appear to be any "easy" way to do this.

The underlying reason for this seems to be that the Collection is simply
implemented as a List (IList) and, therefore, items can be easily moved
about. The TreeView, on the other hand, is (probably) implemented as a
series of linked lists. Moving nodes around in a linked list has never been
a strong point of this data structure.

Since the TreeView is populated by the underlying collection in the first
place, one solution would be to simply clear and re-populate the TreeView
after two nodes are swapped in the collection. However, this would destroy
the "visibile integrity" of the TreeView by collapsing the entire tree.

Another possibility seems to be to make "backup" copies of all the parent
nodes (and sub-nodes), delete all child nodes of the parent, and then re-add
them in the proper order. However, this seems like a lot of work and may
also end up destroying the "visible integrity" of the tree.

Does anybody have any ideas on how to (more) easily swap two sibling nodes
(and their respective sub-nodes) in a TreeView? Any ideas would be much
appreciated!!!

..ARN.
 
If you put references in nodes tags you can just change text on the node
after swapping tags.

HTH
Alex
 
I'm using the TreeNode tags to associate the node with the underlying element
from the collection.

..ARN.
 
Ever have one of those aha moments? I just reailzed what you were saying and
it makes sense. Thanks.

..ARN.
 
hi dude, i'm using this one here but have minor problems..

just try...

private void SwapElements(int index)
{
treeView1.BeginUpdate();
TreeNode n1 = treeView1.Nodes[index];
TreeNode n2 = treeView1.Nodes[index - 1];
treeView1.Nodes.RemoveAt(index);
treeView1.Nodes.RemoveAt(index - 1);
treeView1.Nodes.Insert(index - 1, n1);
treeView1.Nodes.Insert(index, n2);
treeView1.Focus();
treeView1.EndUpdate();
}
 
Back
Top