select nodes of a treeview by code

G

Guest

Hi NG,
I have two treeviews on my form with exactly the same structure, but with
different nodes.
How can I select the same node or index within the second treeview when
selecting a node in the first treeview?

Thanks for answering

Werner
 
M

Mark Erikson

Werner said:
Hi NG,
I have two treeviews on my form with exactly the same structure, but with
different nodes.
How can I select the same node or index within the second treeview when
selecting a node in the first treeview?

Thanks for answering

Werner

Try working your way up the hierarchy, checking for the index of each
TreeNode as you go. Save those indices, then use them to find the
equivalent node in the other treeview. Here's some (untested) C# code
that should get you close:

public TreeNode GetFraternalTwinNode()
{
TreeNode startingNode = treeView1.SelectedNode;
TreeNode currentNode1 = startingNode;
ArrayList indices = new ArrayList();

// Save the indices of all the starting node's ancestors,
// in ascending order
while(currentNode1.Parent != null)
{
indices.Add(currentNode1.Index);
currentNode1 = currentNode1.Parent;
}

// Switch the indices into descending order
indices.Reverse();

// Get the index of the topmost ancestor
int topmostIndex = currentNode1.Index;

// Get the equivalent of the topmost ancestor
TreeNode currentNode2 = treeView2.Nodes[topmostIndex];

// Descend the hierarchy to the equivalent of the starting node
for(int i = 0; i < indices.Count; i++)
{
int currentIndex = (int)indices;
currentNode2 = currentNode2.Nodes[currentIndex];
}

TreeNode finalNode = currentNode2;

return finalNode;
}

Hope this helps!

Mark Erikson
http://www.isquaredsoftware.com
 

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