Hi Meh, Herfried,
|| You can grab the node's 'Index' property value,
|| then get its 'Parent' node, add its index to the node
|| number and so on, until you reach the root node.
This back-up-the-hierarchy method is a good way to get screen positions of a control within a series of containers. It works
because each X, say, is a position relative to the left of the parent, and it doesn't matter whether there are any other controls
inbetween or anywhere else..
Unfortunately it doesn't work with indexes. :-( For example, if a node is the fourth under its parent, its index within the tree
will depend on the number of sub-nodes that each of the other three has.
The hard method is to go back up the hierarchy, and then recurse down each of the nodes that precede the node in question at any
given level.
If all this sound like gobbledegook, just ignore it
If it makes sense to you then so might the following code.
In short, I would recommend that you set the Tag of the Nodes in the tree. This assumes, though, that your Tree contents will
remain stable. Any additions or deletions would spoil the count.
Regards,
Fergus
Private Sub TheTreeView_AfterSelect(ByVal sender As System.Object, _
ByVal e AsSystem.Windows.Forms.TreeViewEventArgs) _
Handles TheTreeView.AfterSelect
Label1.Text = NodePosition (TheTreeView, e.Node)
End Sub
'Determine the position (1-based) of the given Node in its TreeView.
Private Function NodePosition (oTreeView As TreeView, oNode As TreeNode)
Dim iPosInTree As Integer = 0
Do
Dim iNodeIndex As Integer = oNode.Index
iPosInTree = iPosInTree + iNodeIndex + 1
'Get the Parent Node or the TreeView if at the top.
Dim oParentNode As Object = oNode.Parent
If oParentNode Is Nothing Then
oParentNode = oTreeView
End If
'Count the Nodes precding this one on the current level.
Dim I As Integer
For I = 0 To iNodeIndex - 1
iPosInTree = iPosInTree + NumberOfChildren (oParentNode.Nodes (I))
Next
'Go up to the next level.
oNode = oNode.Parent
Loop Until oNode Is Nothing
Return iPosInTree
End Function
Function NumberOfChildren (oNode As TreeNode)
If oNode.LastNode Is Nothing Then
Return 0 'No children
End If
Dim iNumChildren = oNode.LastNode.Index + 1
Dim oSubNode As TreeNode
For Each oSubNode in oNode.Nodes
iNumChildren = iNumChildren + NumberOfChildren (oSubNode)
Next
Return iNumChildren
End Function