Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Creating Access Menu with Tree View Control

The Microsoft Access Project Menu, after completing the Tree View Control, will resemble the image shown below.

In the image above, the third option under the Report Group, Custom Report, is selected and highlighted. The Report Filter Parameter Form is open, overlapping the Menu Screen, ready for the user’s input.

Before we get into that, let’s briefly revisit last week’s lesson. We explored how to organize related items into a hierarchical structure using the Microsoft TreeView control, based on a sample data table.

Last week, I emphasized that related items in the TreeView control’s data do not need to appear next to each other in the table. In this session, we will take that concept further by showing how to update the Relative Keys of child nodes—regardless of the physical position of the records in the table—purely based on their relationship to their parent node IDs.

Here is the data table we worked with and completed in last week’s exercise:

Can you add the following list of items at the end of the above table and update their ParentID field values, so that the TreeView Control display will look like the sample image given below:

New records for the Table item record related field:

  1. Text Field.
  2. Number Field.
  3. Date/Time Field.
  4. Hyperlink Field.

Form-related Controls:

  1. Text Box.
  2. Command Buttons.
  3. Combo Box.
  4. List Box.

Report-related Controls:

  1. Text Box.
  2. Label.
  3. Graph Chart.

Assign ParentID Values to these items so that the Tree View Display looks like the following Image:

Now, we will proceed with the creation of an MS-Access Project Menu and learn what it takes to create one. A simple Menu Image is given below:

This is a simple menu containing three main groups of options: Forms, Report Views, and Macros.

  • Forms Group

    • The first option displays the TreeView control’s menu table records.

    • The second option presents the same records in Continuous Form view.

  • Report Views Group

    • The first option generates a report of product categories from the Categories table in the NorthWind.accdb database.

    • The second option displays the Products List-Price Report.

    • The third option opens a Parameter Form, allowing the user to specify a minimum and maximum list price range to filter the Products List-Price Report data.

  • Macros Processes Group

    • The two options in this group run Macro1 and Macro2, respectively, each displaying a different message.

To implement this menu, we need a Menu Table containing the above option records, along with some additional fields beyond the standard TreeView fields—Unique ID, Description, and ParentID. The image below shows the structure of this menu table:

Create a Table with the above structure, add the above records, and save it with the name Menu.  The ID field is an Auto Number, the PID and Type fields are numeric, while the remaining fields are text.

We are already familiar with the first three fields, Unique ID, Description, and ParentID. Here, the ParentID field name has been shortened to PID for convenience.

We now need four additional fields in the Menu Table:

  1. Type – Stores the Access object type code.

  2. Form – Stores form names (object type code: 1).

  3. Report – Stores report names (object type code: 2).

  4. Macro – Stores macro names (object type code: 3).

Note: While all object names could be stored in a single column, we are using separate fields for clarity. If you decide to use a single column, remember to adjust the VBA code wherever the field names are referenced.

The Type field helps us determine which action to take when a user clicks on an option:

  • If the type is 1, open the form using DoCmd.OpenForm.

  • If the type is 2, open the report using DoCmd.OpenReport.

  • If the type is 3, run the macro using DoCmd.RunMacro.

When we start adding nodes to the TreeView control, we will store both the Type Code and the Object Name for each child node.


Additional Required Tables and Objects.

We will also need two additional data tables—Categories and Products—from the NorthWind sample database.

To save time, a demo database with all required objects and programs is provided at the end of this page for download and testing.


Creating the Forms and Reports

  1. Create two forms based on the Menu Table:

    • Data Entry (single form view)

    • Data View (continuous form view)

  2. Create two reports:

    • Categories – Based on the Categories table.

    • Products Listing – Based on the Products table.

      • Add a long label below the main heading and set its Name property to Range.

  3. Create a small form for filtering products:

    • Add two unbound text boxes.

    • Set their Name property values to Min and Max.

    • Design it as shown in the sample layout below.

Add two Command Buttons as shown above.  Change the Caption Property Value of the first Button to Open Report and the Name Property Value to cmdReport.

Change the Second Command Button’s Caption to Cancel and the Name Property value to cmdCancel.

Display the Code Module of the Form.  Copy and Paste the following Code into the Form Module and save the Form:

Private Sub cmdOpen_Click()
Dim mn, mx, fltr As String
mn = Nz(Me![Min], 0)
mx = Nz(Me![Max], 9999)
If (mn + mx) > 0 Then
    fltr = "[List Price] > " & mn & " And " & "[List Price] <= " & mx
    DoCmd.OpenReport "Products Listing", acViewReport, , fltr, , fltr
Else
    DoCmd.OpenReport "Products Listing", acViewReport
End If

End Sub

Private Sub cmdCancel_Click()
DoCmd.Close
End Sub

When the user specifies a value range by entering the Minimum and Maximum list prices in their respective text boxes, a report filter criterion string is created.

This filter string is:

  • Passed to the Products Listing report as a filter parameter in the DoCmd.OpenReport command.

  • Also sent as the OpenArgs (open argument) parameter.

The filter parameter limits the report data to records that fall within the specified Min and Max price range.
The OpenArgs value is used to update the Range label’s caption when the report opens, so the user can see the filter range they applied.


Copy and paste the following VBA code into the Products Listing report’s code module:

Private Sub Report_Open(Cancel As Integer)
    DoCmd.Close acForm, "Parameter"
    Me.Range.Caption = Nz(Me.OpenArgs, "")
End Sub
  1. Create a new form, with the name frmMenu, and add the Microsoft TreeView Control from the ActiveX Controls List.  Resize the Control as shown in the Design View below:

  2. Change the Tree View control’s name to TreeView0 in the standard Property Sheet.

    Add a Command Button below the Tree View control.

    • Set its Name property to cmdExit.

    • Set its Caption property to Exit.

    Right-click the Tree View control, choose TreeCtrl_Object, and select Properties to open its Property Sheet.

    Update the following property values:

    • Style = 7 (tvwTreeLinesPlusMinusPictureText)

    • Line Style = 1 (tvwRootLines)

    • LabelEdit = 1 (tvwManual)

    Last week, we already updated the first two property values.

    By default, the LabelEdit property is set to 0 – tvwAutomatic. In that mode, clicking a node twice (not double-clicking) puts the node text into edit mode, allowing you to change it. However, this does not update the underlying data source field.

    Changing the value to 1 – tvwManual disables this automatic edit mode, preventing accidental changes to node text.

    You can also make this change programmatically by adding the following lines to the Form_Load() event procedure:

With Me.TreeView0.Object
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines	
    .LabelEdit = tvwManual
End With

Last week, we used the Form_Load() event procedure to read the Tree View node values and create both the root-level and child nodes. We will use the same procedure here, with a few additional lines of code.

In addition, we need to handle the Node_Click() event to determine which option the user has selected.

Copy and paste the following VBA code into the form’s module, then save the form:

Option Compare Database
Option Explicit

Dim tv As MSComctlLib.TreeView
Const KeyPrfx As String = "X"

Private Sub Form_Load()
Dim db As Database
Dim rst As Recordset
Dim nodKey As String
Dim PKey As String
Dim strText As String
Dim strSQL As String

Dim tmpNod As MSComctlLib.Node
Dim Typ As Variant

Set tv = Me.TreeView0.Object
tv.Nodes.Clear


‘Change the TreeView Control Properties
With tv
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
End with

    strSQL = "SELECT ID, Desc, PID, Type,Macro,Form,Report FROM Menu;"

Set db = CurrentDb
Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)

Do While Not rst.EOF And Not rst.BOF
    If Nz(rst!PID, "") = "" Then
        nodKey = KeyPrfx &  CStr(rst!ID)
        strText = rst!Desc
      Set tmpNod = tv.Nodes.Add(, , nodKey, strText)
      
      'Root-Level Node Description in Bold letters
      With tmpNod
        .Bold = True
      End With
    Else
        PKey = KeyPrfx & CStr(rst!PID)
        nodKey = KeyPrfx & CStr(rst!ID)
        strText = rst!Desc
        Set tmpNod = tv.Nodes.Add(PKey, tvwChild, nodKey, strText)
     
     'Check for the presense of Type Code
        If Nz(rst!Type, 0) > 0 Then
            Typ = rst!Type
            Select Case Typ
                Case 1 'save type Code & Form Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Form
                Case 2 'save type Code & Report Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Report
                Case 3 'save type Code & Macro Name in Node Tag Property
                    tmpNod.Tag = Typ & rst!Macro
            End Select
      End If
        
    End If
    rst.MoveNext
Loop
rst.Close

Set rst = Nothing
Set db = Nothing

End Sub

Private Sub cmdExit_Click()
If MsgBox("Close Menu Form? ", vbYesNo, "cmdExit_Click()") = vbYes Then
    DoCmd.Close
End If
End Sub

Private Sub TreeView0_NodeClick(ByVal Node As Object)
Dim varTag, typeid As Integer
Dim objName As String, nodOn as MSComctlLib.Node

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If


‘Reset the earlier highlight to normal
For Each nodOn In tv.Nodes
	nodOn.BackColor = vbWhite
    nodOn.ForeColor = vbBlack
    
    ‘changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
    
    ‘—Highlight code ends-
    varTag = Nz(Node.Tag, "")
    
If Len(varTag) > 0 Then
    typeid = Val(varTag)
    objName = Mid(varTag, 2)
End If

Select Case typeid
    Case 1
        DoCmd.OpenForm objName, acNormal
    Case 2
        DoCmd.OpenReport objName, acViewPreview
    Case 3
        DoCmd.RunMacro objName
End Select
End Sub

The Tree View object is declared in the global declaration area of the module. A constant variable, KeyPrfx, is defined with the value "X".

The Form_Load() event procedure from last week’s article has been updated with additional code. I have added comments to the new segments to indicate their purpose, and I will explain them in detail.

The procedure begins by declaring the Database, Recordset, and four String variables. The next two lines declare a temporary Node object (tmpNod) and a Variant variable named Typ.

The TreeView object tv is then set to reference the TreeView0 control on the form. Any existing nodes in TreeView0 are cleared using: tv.nodes.clear statement

tv.nodes.clear

This ensures we start with a clean slate before reloading all nodes.

Finally, we have implemented code to modify the Tree View control’s properties programmatically, instead of setting them manually in the property sheet.

With tv
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
End With 

The Tree View font is set to Verdana for a cleaner look. In addition, we have implemented functions that allow all menu groups to be expanded or collapsed with a single click, instead of manually expanding or collapsing each group individually.

The SQL string has been updated to include the new fields—Type, Form, Report, and Macro—from the Menu table.

When the procedure runs, the first record in the Menu table is checked for a PID value.

  • If the PID field is empty, it is treated as a root-level node. The record is added to the Tree View as a root node, and its reference is stored in the tmpNod object. To visually distinguish root nodes from child nodes, the Bold property is set to True.

  • If the PID field contains a value, the record is treated as a child node. In this case, the program checks the Type field value. If it contains 1, 2, or 3, the corresponding object name is taken from the Form, Report, or Macro field, prefixed with its Type code (e.g., "1Data Entry", "2Categories", "3MyMacro"), and stored in the node’s Tag property.

The Tag property—available in most Access controls such as text boxes, labels, and command buttons—allows us to store hidden, custom data with each control. In this case, it serves as a convenient way to store both the Type code and object name for later use.

The cmdExit_Click() procedure prompts the user for confirmation and closes the menu form if the response is affirmative.

When a user clicks a child node, the program retrieves the value stored in the node’s Tag property. Based on the Type code, it determines whether to open a form, run a report, or execute a macro. This logic is implemented in the TreeView0_NodeClick() event procedure.

Private Sub TreeView0_NodeClick(ByVal Node As Object)
Dim varTag, typeid As Integer
Dim objName As String, nodOn as MSComctlLib.Node

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If

‘Reset the earlier lighlight to normal
For Each nodOn In tv.Nodes
  nodOn.BackColor = vbWhite 
  nodOn.ForeColor = vbBlack
Next nodOn

‘changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
‘—Highlight code ends-

varTag = Nz(Node.Tag, "")
If Len(varTag) > 0 Then
    typeid = Val(varTag)
    objName = Mid(varTag, 2)
End If

Select Case typeid
    Case 1
        DoCmd.OpenForm objName, acNormal
    Case 2
        DoCmd.OpenReport objName, acViewPreview
    Case 3
        DoCmd.RunMacro objName
End Select
End Sub

The Click() event procedure receives a reference to the clicked node through the Node parameter. At the start of the procedure, a few variables are declared for later use.

The next section checks whether the clicked node is currently expanded or collapsed.

Normally, to expand a node and reveal its child nodes, you either click the plus (+) symbol to the left of the node or double-click the node itself. Likewise, double-clicking the node again or clicking the minus (–) symbol collapses it, hiding the child nodes.

With the following code segment, this process is simplified—allowing you to expand or collapse a node with a single click instead of the usual two-step interaction.

If Node.Expanded = False Then
    Node.Expanded = True
Else
    Node.Expanded = False
End If 

The next six executable lines ensure that the Node that received the Click remains highlighted.

‘Reset the earlier Highlight to Normal
For Each nodOn In tv.Nodes
  nodOn.BackColor = vbWhite 
  nodOn.ForeColor = vbBlack
Next nodOn
‘Changes BackColor to light Blue and ForeColor White
    tv.Nodes.Item(Node.Key).BackColor = RGB(0, 143, 255)
    tv.Nodes.Item(Node.Key).ForeColor = vbWhite
‘—Highlight code ends-

Next, the varTag variable is assigned the value from the node’s Tag property. If this value is not empty, it is split into two parts:

  • The numeric portion is extracted and stored in the Typid variable.

  • The object name portion is stored in the objName variable.

Based on the value of 'Typid'The appropriate DoCmd action is executed to open a form, open a report, or run a macro.

We will also add two additional command buttons at the top of the menu:

  • One button to expand all nodes with a single click.

  • Another button to collapse all nodes with a single click.

  1. Place these two buttons in the top area of the TreeView control, as shown in the design layout below.

  2. Change the Name Property Value of the left Command Button to cmdExpand and the Caption to Expand All.

  3. Similarly, change the right-side Command Button’s Name Property to cmdCollapse and the Caption to Collapse All.
  4. Copy and paste the following VBA Code below the existing Code in the frmMenu Form Module and save the Form.
Private Sub cmdExpand_Click()
Dim Nodexp As MSComctlLib.Node

For Each Nodexp In tv.Nodes
    If Nodexp.Expanded = False Then
        Nodexp.Expanded = True
    End If
Next Nodexp
End Sub


Private Sub cmdCollapse_Click()
Dim Nodexp As MSComctlLib.Node

For Each Nodexp In tv.Nodes
    If Nodexp.Expanded = True Then
        Nodexp.Expanded = False
    End If
Next Nodexp
End Sub

At the beginning of the cmdExpand_Click() event procedure, we declare a TreeView Node object named NodExp. The For…Next loop then iterates through each node, checking whether it is already expanded. If a node is not expanded, its Expanded property is set to True.

The cmdCollapse_Click() event follows the same approach. However, instead of expanding nodes, it checks if they are currently expanded, and if so, sets their Expanded property to False.

With these two commands, you can:

  • Instantly expand the entire TreeView, making all child nodes visible.

  • Collapse all child nodes so that only the root-level nodes remain visible.

If you have followed each design step carefully, your menu should now look like the finished menu image shown at the top.

Back in 2007, I designed a similar menu for a Vehicle Service Contract System project. That version used a Tab Control with multiple pages. Each page displayed 10 or more options, and the user could switch pages by clicking command buttons arranged along either side of the menu. The command buttons on the right would change dynamically based on the selection made from the left side—creating a flexible, context-sensitive menu system.

You can find the Menu Design with Tab Control Article on this Link:https://www.msaccesstips.com/2007/06/control-screen-menu-design.html


CLASS MODULE

  1. MS-Access Class Module and VBA
  2. MS-Access VBA Class Object and Arrays
  3. MS-Access Base Class and Derived Objects
  4. VBA-Base Class and Derived Object-2
  5. Base Class and Derived Object Variants
  6. MS-Access Recordset and Class Module
  7. Access Class Module and Wrapper Classes
  8. Wrapper Class Functionality

Share:

Microsoft TreeView Control Tutorial

A. TreeView Control Tutorial.

The Microsoft TreeView Control, part of the Microsoft Windows Common Controls library, is a powerful object for displaying related data in a hierarchical structure of nodes. It can represent information such as index entries and sub-entries, folder structures similar to Windows Explorer’s left pane, or any list of related items—complete with tree lines, checkboxes, and graphical icons.

Alongside the TreeView Control, we will also be using the ListView and ImageList controls, which are part of the Windows ActiveX Controls suite, to enhance functionality and presentation in Microsoft Access.

In the coming weeks, we’ll explore how to build and customize a TreeView Control from scratch. To give you a preview, I’ll share some sample TreeView demo images showcasing what we’ll be working toward.

B. Sample Demo Images.

      Nodes in the Collapsed state.

  1. The Sample Demo TreeView Image with all Nodes in Collapsed form.

     Nodes in the Expanded View.

  2. The above TreeView Control Nodes are in the expanded view.

    With Arrowhead Image Icons.

  3. The TreeView Sample Display, with arrowhead Image Icons displayed to the left of each Node Text.

    Folder Images for Root-Level Nodes, others with arrowheads.

  4. Next, we’ll look at a TreeView display integrated with linked data in a subform. The root-level nodes are visually enhanced with two images: a closed folder icon in the default state, and an open folder icon when the node is clicked. Selecting a root-level node not only changes the icon but also expands it to reveal its child nodes.

    The subform dynamically updates to display related information based on the selected root-level node. Additionally, selecting certain child nodes can trigger the display of another form—normally kept hidden—that provides further related details.

    TreeView and ListView Controls.

  5. In the next form layout, there are two panels. The left panel contains the TreeView control, which displays nodes representing product categories. When a category node is clicked, the right panel—comprising the ListView control—updates to display the related product items, along with their quantities and list prices in separate columns.

C. Creating Sample Data for Trial Run.

Let us try out the TreeView Control with some sample data shown below, based on the first two images displayed at the beginning of this Page.

The sample data table contains three fields:

  1. ID – An AutoNumber field that generates unique ID numbers. AutoNumber is used here for convenience, but regardless of the type, each record in the table must have a unique ID value. If the ID is numeric, it should be converted to a string before adding it to the TreeView control.

  2. Description (Desc) – Contains the node descriptions. The entries in this column are logically related to one another.

  3. ParentID – A numeric field that identifies the parent node for each record. This value should also be converted to a string before using it in the TreeView control.

To build the hierarchy, we need to understand how the description values relate to one another. Based on these relationships, appropriate values are entered into the ParentID field.

For example, the logical hierarchy could represent:

  • Authors → Publishers → Bookstores where the books are sold.

  • Members of a family tree.

  • Product categories → Products → Stock → Price.

This related information may not always exist in a single column or table—it could be spread across multiple columns or even different tables.

The ParentID field plays a crucial role in defining the hierarchical arrangement of nodes. If the ParentID field is empty, the record is treated as a root-level node. A child node must always have its ParentID populated with the ID value of its parent record.

A root-level node can have one or more child nodes, and a child node can, in turn, have its own child nodes, creating multiple hierarchy levels.

We will first load the sample data into a TreeView control to view its initial arrangement. Then, by filling in the ParentID field with related IDs, we can reorganize the nodes into the desired logical order.

D. Windows Common Controls Library File

  1. First, open an existing database or create a new one.
  2. Press ALT + F11 to open the VBA editor, then choose References… from the Tools menu.
  3. In the list of available references, look for Microsoft Windows Common Controls and check its box to select it.

    • If the file is not listed, click Browse… and locate MSCOMCTL.OCX in the Windows system directory.

    • In Windows 7 (64-bit), you will typically find it in the SysWOW64 folder.

    • Once selected, click OK to close the References dialog.

  4. Create a Table with the following structure:

  5. Save the Table with the name Sample.

  6. Fill the Table with the sample data of 12 records as shown in the data view Image above.

    E. Creating TreeView Control on Form

  7. Create a New blank Form.

  8. Click on the ActiveX Controls button from the Controls Group, find the Microsoft TreeView Control, then select it.

  9. Click OK to insert a TreeView control on the Form.

  10. Drag the TreeView control slightly down and to the right to leave some space along the top and left edges.

    Next, use the bottom-right sizing handle to stretch the control toward the right and downward, enlarging it to match the proportions shown in the sample image below.

  11. Display the control's Property Sheet, and change its Name Property Value to TreeView0, if it is different.

  12. Display the VBA Editing Window of the Form.

  13. F. Access VBA Code.

  14. Copy and paste the following VBA Code into the Module, overwriting the existing lines of code there:
    Option Compare Database
    Option Explicit
    
    Dim tv As MSComctlLib.TreeView
    Const KeyPrfx As String = "X"
    
    Private Sub Form_Load()
    Dim db As Database
    Dim rst As Recordset
    Dim strSQL As String
    Dim nodKey As String
    Dim ParentKey As String
    Dim strText As String
    
    Set tv = Me.TreeView0.Object
    
    strSQL = "SELECT ID, Desc, ParentID FROM Sample;"
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSQL, dbOpenDynaset)
    
    Do While Not rst.EOF And Not rst.BOF
        If Nz(rst!ParentID, "") = "" Then
            nodKey = KeyPrfx & CStr(rst!ID)
            strText = rst!Desc
            ‘Add the TreeView Root Level Nodes
            tv.Nodes.Add , , nodKey, strText
        
        Else
            ParentKey = KeyPrfx & CStr(rst!ParentID)
            nodKey = KeyPrfx & CStr(rst!ID)
            strText = rst!Desc
            ‘Add the Record as Child Node
            tv.Nodes.Add ParentKey, tvwChild, nodKey, strText 
            
        End If
        rst.MoveNext
    Loop
    rst.Close
    
    Set rst = Nothing
    Set db = Nothing
    
    End Sub
    
    
  15. Save the Form with the name frmSample, but don’t close the VBA Window.

    G. VBA Code Review – Line by Line

    Let’s take a quick look at the VBA code and understand what it does.

    In the Global Declaration area of the Form module:

    • tv is declared as a TreeView object.

    • KeyPrfx is declared as a String constant with the value "X".

    The TreeView Node’s Key must always be a string and must contain at least one non-numeric character. Since our sample table’s key values are purely numeric, we convert them to strings and prefix them with the letter "X".

    • Example: 1"X1"

    • Simply converting a numeric value to a string (without an alphabet) will not be accepted as a valid Node key.

    Note: If the Node Key and Parent Key are already in alphabetic or alphanumeric form, conversion is unnecessary. All Node keys must still be unique.


    In the Form_Load() event procedure:

    1. Database and Recordset objects are declared, along with four string variables.

    2. The statement:

      Set tv = Me.TreeView0.Object

      assigns the TreeView0 control on the form to the object variable tv.

    3. OpenRecordset() Opens the sample table records using the SQL string strSQL.

    4. The Do While...Loop ensures the recordset is processed only if it is not empty; otherwise, the loop exits and the procedure ends.


    Determining Node Type

    • If the ParentID field is empty, the record becomes a Root-level Node.

      • A Root Node needs only a unique Key and Text (from the ID and Desc fields).

    • If the ParentID has a value, the record becomes a Child Node of either a Root Node or an upper-level Child Node.


    Building the Node Key & Text

    • nodKey is created by converting the ID field to a string and prefixing it with "X". Example: ID = 1nodKey = "X1".

    • strText stores the Desc field value. This keeps the Nodes.Add() parameters are short and readable, especially when field references are long.


    Adding the Node

    The statement:

    tv.Nodes.Add(...)

    calls the Add() method of the TreeView’s Nodes collection to insert the node into TreeView0 on frmSample.


    Syntax of Add() method:

    tv.Nodes.Add([Relative], [Relationship], [Key], [Text], [Image], [SelectedImage]) As Node
    • All six parameters are optional.

    • Calling it without parameters adds an empty Root Node (a blank tree line).

    Requirements:

    • Root Node: Needs only Key and Text.

    • Child Node: Requires both [Relative] and [Relationship].

      • Omitting either adds it as a Root Node (no error occurs).

      • [Relative] is the Node Key of the existing parent (from ParentID).

      • [Relationship] is the constant tvwChild (value 4), identifying it as a child of the parent node.

The other Constant values for the Relationship Argument are used to position the Child Nodes in a specific location.  Constant Values are as follows:

tvwFirst = 0,  places it as the first Node, at the level of the relative Node.

tvwLast = 1,  places as the last Node, at the level of the relative Node.

tvwNext = 2,  places the Node after a specified Node.

tvwPrevious = 3, places the Node immediately preceding the specified Node.

Note: You can experiment with different values in the Relationship argument and run the code in Debug Mode, keeping the VBA editor and the form in Normal View side by side. Observe how the nodes are arranged during each iteration of the code. This will help you understand the effect of each relationship type.

This knowledge becomes useful when editing the TreeView—such as deleting an item, inserting another item in its place, or adding a new node at a specific location.

A node referenced in the [Relative] argument must already exist in the Nodes collection before you can add a child node to it. Otherwise, it will generate an error.

The process continues until all records in the recordset have been processed.

Note: You may need to review the VBA code again after running the demo to reinforce your understanding.

H. The First Trial Run.

Open the Form in Normal View.  The Trial Run result looks like the Image given below.

It doesn’t look much different from a regular list box at the moment. This is because we have not yet assigned any values in the ParentID field in our sample table. To arrange items hierarchically in the TreeView control, we must define relationships between the rows in the table.


I. Understanding the Relationship Between Records

Open the sample table and examine how the records relate to each other.

We will keep the Database item as a root node. The database object also contains several top-level objects—Application, DBEngine, Workspaces collection, and Databases collection—which we have not included here.

Next, we have the Tables group item with an ID value of 2.

In the following records, we see the Table, Fields, and Field items, which are all related to the Tables group. Our goal is to place the Table, Fields, and Field records under the parent node Tables (ID value 2).

In this hierarchy, the Tables record becomes the parent node, and the Table, Fields, and Field records become its child nodes.


J. Updating the ParentID Field

To achieve this structure, we need to update the ParentID field for the Table, Fields, and Field records with the value 2 (the node key of Tables).

Update only these records, then close the table. Once completed, your records should look like the example shown in the image below.

Now, open frmSample in Form View and check the TreeView control.
At first glance, the display will look exactly the same as before—no visible changes.
However, the updates you made are already in effect; they’re just not reflected visually yet.


K. The Property Sheet of the TreeView Control

The TreeView control has its own Property Sheet, and these settings influence how the control appears. We’ll adjust one of these properties before returning to the TreeView to see the change.

  1. Switch frmSample to Design View.

    1. Right-click the TreeView control.

    2. From the shortcut menu, highlight TreeCtrl_Object and select Properties.

    3. The Property Sheet will now appear, as shown below.

    4. The Settings on this Property Sheet change the appearance of the TreeView Display.

      The left-side top Property Style is already set with the maximum features available, Option-7 (tvwTreeLinesPlusMinusPictureText).

    5. Change the LineStyle Property Value = 1 (tvwRootLines) and click the Apply button, then click OK to close the Property Sheet.

      L. Running After the LineStyle Property Change

    6. Save the form and open it in Normal View.
      You’ll now see the tree lines displayed correctly.

    7. The Tables node now shows a plus (+) sign to its left, indicating that it has one or more child nodes at the next level, which are currently collapsed.

      • Click the plus (+) sign to expand the node and reveal all child nodes sharing the same ParentID.

      • Click the minus (–) sign to collapse them again, hiding the child nodes and changing the symbol back to a plus (+).

      When expanded, the display will resemble the image shown below:

      Updating the ParentID for Other Records.

      Next, we will establish the parent–child relationships for the remaining records.

      1. Forms and Controls

        • Update the ParentID field of the Form, Controls, and Control records with the Forms record’s ID value (Node-Key).

        • This ensures that these records will appear under the Forms node as its child nodes in the TreeView.

      2. Reports and Controls

        • Similarly, update the ParentID field of the Report and Control records with the Reports record’s ID value (Node-Key).

        • This positions them under the Reports node as its child nodes.

    8. Once the updates are complete, your Sample Table should match the ParentID values shown in the illustration below:

      After applying the above changes, open the form and expand all the nodes in the TreeView. The display should now resemble the image shown below, with every parent node and its corresponding child nodes fully visible.

      All child nodes related to the root-level nodes—Tables, Forms, and Reports—are grouped under their respective parent nodes. However, a child node may also have a parent node, a grandparent node, or even a great-grandparent node, depending on the hierarchy.

      N. Arranging All Objects in a Logical Hierarchical Order
      Let’s take the first root-level node, Tables, as an example. Logically:

      • Field (record ID 5) is directly related to the Fields collection (record ID 4).

      • The Fields collection is related to the Table.

      • The table is part of the Tables collection.

      This means that each item in the group (record numbers 5 through 2) is connected one step upward to the next level in the hierarchy.

      Next, we will position these child nodes under their respective parent nodes in the correct order and see how the arrangement appears in the TreeView control.

    9. Open your Sample Table and change the ParentID values of the Tables related to Child Records as shown below:

    10. The record Field with ID 5 has Fields (record ID 4) as its parent. Therefore, we update the ParentID field of record 5 with the value 4.

      Similarly:

      • Record 4 (Field) has record 3 (Table) as its parent, so we set its ParentID to 3.

      • Record 3 (Table) has record 2 (Tables) as its parent, so we set its ParentID to 2.

      Note: The records do not have to appear next to each other in the table to establish this hierarchy.

      After making these changes, save the table and open frmSample to view the results. Your TreeView display should now resemble the image shown below, with all nodes expanded.

    The Child-Node of a Root-level Node can be a Parent-Node to its own Child or Children.  This way, it can go several steps down the tree.

    Change the other two groups of Child Node's ParentID field values to look like the Image given above.

    Download TreeView Demo Database.

    DICTIONARY OBJECT

    1. Dictionary Objects Basics
    2. Dictionary Object Basics-2
    3. Sorting Dictionary Object Keys and Items
    4. Display Records from Dictionary
    5. Add Class Objects as Dictionary Items
    6. Update Class Object Dictionary Item
Share:

MS-Access Class-Module Tutorial Index

We are planning a series of Tutorials on Microsoft Windows Tree View Control Programming in Microsoft Access and will publish the Series in the coming weeks.

In the meantime, I thought it was appropriate to organize the earlier Tutorial Links, on Class Module and Event Handling Programming Series, of Articles on a separate page, for easy access in published order.

This is helpful for those who would like to go through the Tutorials on a gradual progressive way of learning. Those tutorials started from the Basic-level and progressed through the more advanced stage of programming levels. The learning curve should start from the base level and go up to the top to understand the changes at each level. Once you are familiar with the Object or Control, you may continue to learn further by experimenting with them on your own Programs or Projects.

After all, there is more than one way to solve a problem in Computer Programming based on the programmer’s understanding of the Language, Skill, and Experience.  

CLASS MODULE TUTORIALS

  1. MS-Access Class Module and VBA
  2. MS-Access VBA Class Object and Arrays
  3. MS-Access Base Class and Derived Objects
  4. VBA-Base Class and Derived Object-2
  5. Base Class and Derived Object Variants
  6. MS-Access Recordset and Class Module
  7. Access Class Module and Wrapper Classes
  8. Wrapper Class Functionality

COLLECTION OBJECT

  1. MS-Access and Collection Object Basics
  2. MS-Access Class Module and Collection Objects
  3. Table Records in Collection Object

DICTIONARY OBJECT

  1. Dictionary Objects Basics
  2. Dictionary Object Basics-2
  3. Sorting Dictionary Object Keys and Items
  4. Display Records from Dictionary
  5. Add Class Objects as Dictionary Items
  6. Update Class Object Dictionary Item

MS-ACCESS EVENT HANDLING TUTORIALS

  1. Withevents MS-Access Class Module
  2. Withevents and Defining Your Own Events
  3. Withevents Combo List Textbox Tab
  4. Access Form Control Arrays And Event
  5. Access Form Control Arrays And Event-2
  6. Access Form Control Arrays And Event-3
  7. Withevents in Class Module for Sub-Form
  8. Withevents in Class Module and Data
  9. Withevents and Access Report Event Sink
  10. Withevents and Report Line Hiding
  11. Withevents and Report-line Highlighting
  12. Withevents Texbox and Command Button
  13. Withevents Textbox Command Button
  14. Withevents and All Form Control Types


Download Android App MSA Guru Version of LEARN MS-ACCESS TIPS AND TRICKS, from the Google Play Store.

Download Link: MSA Guru  Size: 2.3MB

Share:

PRESENTATION: ACCESS USER GROUPS (EUROPE)

Translate

PageRank

Post Feed


Search

Popular Posts

Blog Archive

Powered by Blogger.

Labels

Forms Functions How Tos MS-Access Security Reports msaccess forms Animations msaccess animation Utilities msaccess controls Access and Internet MS-Access Scurity MS-Access and Internet Class Module External Links Queries Array msaccess reports Accesstips WithEvents msaccess tips Downloads Objects Menus and Toolbars Collection Object MsaccessLinks Process Controls Art Work Property msaccess How Tos Combo Boxes Dictionary Object ListView Control Query VBA msaccessQuery Calculation Event Graph Charts ImageList Control List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button Report msaccess menus msaccessprocess security advanced Access Security Add Auto-Number Field Type Form Instances ImageList Item Macros Menus Nodes RaiseEvent Recordset Top Values Variables Wrapper Classes msaccess email progressmeter Access2007 Copy Excel Export Expression Fields Join Methods Microsoft Numbering System Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup database function msaccess wizards tutorial Access Emails and Alerts Access Fields Access How Tos Access Mail Merge Access2003 Accounting Year Action Animation Attachment Binary Numbers Bookmarks Budgeting ChDir Color Palette Common Controls Conditional Formatting Data Filtering Database Records Defining Pages Desktop Shortcuts Diagram Disk Dynamic Lookup Error Handler External Filter Formatting Groups Hexadecimal Numbers Import Labels List Logo Macro Mail Merge Main Form Memo Message Box Monitoring Octal Numbers Operating System Paste Primary-Key Product Rank Reading Remove Rich Text Sequence SetFocus Summary Tab-Page Union Query User Users Water-Mark Word automatically commands hyperlinks iSeries Date iif ms-access msaccess msaccess alerts pdf files reference restore switch text toolbar updating upload vba code