Color scheme: Dark
You are here: start » en » Documentation » Microsoft Access development tools » WKL Forms Object Library » WKL Forms Object Library how-to guides » How to: Save and restore the view

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 LoadFromFile on a tree that has a RecordSource, it applies only the state (expanded, selection, check marks) to the record source's nodes; without a RecordSource, 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.
  • wffAuto writes XML for a file name ending in .xml and JSON otherwise; when loading, it detects the format from the content.
  • AsJSON returns a WKL Office JSON JDoc, so WKL Office JSON must be registered.
  • A tree loaded from a file doesn't write changes back, even with AutoSave.
en/wiki/msaccess/comctl/how-to/save-and-restore-the-view.txt · Last modified: by Wolfgang van der Stille