Hi Jp,
This will select a node in the treeview that corresponds to the current record on the Main form (I'm assuming there is only one form involved, i.e. no subform), expand any parent nodes the selected node may have, and highlight the selected node. Be sure the "HideSelection" property of the ocx is set to 'No' ('Yes' is the default).
Private Sub Form_Current()
On Error GoTo ErrorHandler
' Get a refernece to the TreeView control
' on the Main form.
Set oTreeView = Me!TreeView1
If Not oTreeView Is Nothing Then
Dim strKey As String
strKey = Me!ItemText
Set oNode = oTreeView.Nodes(strKey)
oTreeView.SelectedItem = oNode
oNode.EnsureVisible
End If
Exit Sub
ErrorHandler:
If Err.Number = 35601 Then 'Element not found
MsgBox "There is no Node key corresponding to the current record."
Exit Sub
Else
MsgBox Err.Source & "-->" & Err.Description, , "Error"
End If
End Sub
To make this work, you have to reference the nodes collection by node key, which mean the node key has to be set as you add each node to the nodes collection. I'm basing the Main form's recordset on a single table with some real simple data like:
Code:
"ItemID" "ItemText"
1 "Parent1"
2 "Parent2"
3 "Parent3"
4 "Child1"
5 "Child2"
6 "Child3"
7 "Child4"
8 "Child5"
9 "Child6"
So as each node is added to the nodes collection, its key gets set to a corresponding data element, like:
Private Sub Form_Load()
Dim oNode As Node
Dim i As Integer
'Add method arguments
'object.Add(relative, relationship, key, text, image, selectedimage)
For i = 1 To 3
Set oNode = TreeView1.Nodes.Add(, , "Parent" & CStr(i), "Parent" & CStr(i))
Next i
Set oNode = TreeView1.Nodes.Add(1, 4, "Child1", "Child1")
Set oNode = TreeView1.Nodes.Add(1, 4, "Child2", "Child2")
Set oNode = TreeView1.Nodes.Add(2, 4, "Child3", "Child3")
Set oNode = TreeView1.Nodes.Add(2, 4, "Child4", "Child4")
Set oNode = TreeView1.Nodes.Add(3, 4, "Child5", "Child5")
Set oNode = TreeView1.Nodes.Add(3, 4, "Child6", "Child6")
End Sub
I hard coded this stuff just to keep it simple, but you're probably using some sort of loop to populate your treeview from a recordset, in which case just to something like:
Set oNode = TreeView1.Nodes.Add()
With oNode
.Key = "Key_" & rst("ItemText") 'or ItemID, which ever you prefer
.Text = rst("ItemText")
End With
Once the key is set, you should be good to go.
HTH,
Bob