How to: Save and restore the view
Preserve each user's expanded nodes and selection between sessions, or save a whole tree, including its nodes.
Requires WKL Forms Object Library 1.23 or later.
Solution overview
Layout returns the view state (expanded nodes and selection) as text, without the nodes;
assigning that text restores the view. SaveToFile, SaveToString, SaveToStream, and AsJSON
save the nodes together with their state (expanded, selected, checked) as JSON or XML, and the
matching LoadFrom… members load them back.
Implementation
Remember each user's view in a table tblViewState (UserName TEXT, FormName TEXT, Layout MEMO):
Private Sub Form_Close()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM tblViewState WHERE UserName = '" & Environ$("USERNAME") & "' AND FormName = '" & Me.Name & "'")
If rs.EOF Then rs.AddNew Else rs.Edit
rs!UserName = Environ$("USERNAME"): rs!FormName = Me.Name
rs!Layout = Me!Tree1.Object.Layout
rs.Update
End Sub
Private Sub Form_Load()
Dim saved As Variant
saved = DLookup("Layout", "tblViewState", "UserName = '" & Environ$("USERNAME") & "' AND FormName = '" & Me.Name & "'")
If Not IsNull(saved) Then Me!Tree1.Object.Layout = saved
End Sub
Save a complete tree to a file and load it into an unbound tree:
Me!Tree1.Object.SaveToFile CurrentProject.Path & "\regions.json" ' in another form, a WklTreeView without RecordSource: Me!Tree2.Object.LoadFromFile CurrentProject.Path & "\regions.json"
Remarks
- When you call
LoadFromFileon a tree that has aRecordSource, it applies only the state (expanded, selection, check marks) to the record source's nodes; without aRecordSource, it builds an unbound tree from the nodes in the file. - Values keep their VBA data type and are written regardless of regional settings, so the keys match the database again after loading.
wffAutowrites XML for a file name ending in.xmland JSON otherwise; when loading, it detects the format from the content.AsJSONreturns a WKL Office JSONJDoc, so WKL Office JSON must be registered.- A tree loaded from a file doesn't write changes back, even with
AutoSave.
Related topics
en/wiki/msaccess/comctl/how-to/save-and-restore-the-view.txt · Last modified: by Wolfgang van der Stille