synchronize two treeviews

quioske

Active member
Joined
Feb 25, 2008
Messages
27
Programming Experience
1-3
Hi all ,
i have two treeview in vb.net
i have the selected node index in treeview1

then i want to select the node at same index in treeview2 autmatically

is anyone there
 
As you know each node has its own Nodes collection, the index is only valid within the local collection. To sync the other tree this information is not enough, you need to know in which collection to select that index. Below example show the indexes of the different nodes in the different collections of a tree. So if you have node index 1, which node is that?
....root(0)
........child(0)
............child(0)
............child(1) <--- this?
............child(2)
........child(1) <--- this?
............child(0)
............child(1) <--- this?
....root(1) <--- this?
........child0
I see only two solutions, the first is easy and works if the trees have same number of nodes and the second tree is expanded. Using NodeMouseClick event and GetNodeAt method you can select the node in other tree that is at same location as the one clicked in first tree:
VB.NET:
Expand Collapse Copy
Private Sub TreeView1_NodeMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _
Handles TreeView1.NodeMouseClick        
    Me.TreeView2.SelectedNode = Me.TreeView2.GetNodeAt(e.Location)
End Sub
The second solution is to get the indexes all the way up to root, then follow that route down the second tree:
VB.NET:
Expand Collapse Copy
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) _
Handles TreeView1.AfterSelect
    Dim node As TreeNode = e.Node
    'get the index path
    Dim idx As New Stack(Of Integer)
    While node IsNot Nothing
        idx.Push(node.Index)
        node = node.Parent
    End While
    'walk the index path
    node = Me.TreeView2.Nodes(idx.Pop)
    For i As Integer = 1 To idx.Count
        If node.Nodes.Count > idx.Peek Then
            node = node.Nodes(idx.Pop)
        Else
            Exit Sub
        End If
    Next
    Me.TreeView2.SelectedNode = node
End Sub
 
Back
Top