Microsoft Access VBA Tutorials for self-paced learning, Class Modules, SQL Techniques, and AI Integration Guides.

ListView Control with Ms-Access TreeView

Using the ListView Control in TreeView.

In this episode of the TreeView Control Tutorial, we introduce the Microsoft Access ListView Control Project. The primary objective is twofold:

  1. Populate the TreeView Control with Product Category items.

  2. When a Category Node is selected, filter the related Product records from the Products Table and display them in the ListView Control.

Each Product record is presented with its field values arranged neatly across multiple columns, making the data easier to browse and analyze.

We are familiar with TreeView, ImageList, and ImageCombo Controls and worked with them in earlier Episodes. 

The ListView Control will display data from three selected fields, arranged across three separate columns. Each column will include a header and additional properties such as report icons and tooltip text.

Since a Product record contains several fields, displaying all of them in the limited space of the ListView Control is not practical. Instead, the ListView Control serves as a concise overview. When a user selects an item in the ListView, a separate Form opens displaying the chosen Product record's complete details.

In summary, this Project demonstrates how to integrate the TreeView, ListView, and ImageList Controls to create a structured and interactive interface for browsing and managing product data.

The ListView Control shares many characteristics with the Microsoft Access ListBox Control. Like the ListBox, it can display multiple columns of related values, each neatly arranged under its respective column header. The ColumnWidth property for each column ensures the field values have adequate space to display. In addition, each ListView item is interactive—responding to clicks—allowing further actions such as opening a Form, running a Report, executing a Macro, or calling other functions as needed.

Links to the earlier Tutorial Sessions.

  1. Microsoft TreeView Control Tutorial.
  2. Creating an Access Menu with a TreeView Control.
  3. Assigning Images to TreeView Control.
  4. Assigning Images to TreeView Control-2 (creating ImageList Control shareable with other Projects.)
  5. TreeView Control Check-Mark Add, Delete Nodes.
  6. TreeView ImageCombo Drop-Down Access Menu.
  7. Re-arrange TreeView Nodes by Drag and Drop.

Articles on Access ListBox Control.

  1. In Microsoft Access, the ListBox Control is a versatile tool for displaying information in many contexts. We have explored its use in several creative ways—for example:

    • Designing custom-made Form Wizards and Report Wizards.

    • Creating Hyperlinks within ListBox items.

    • Generating list items dynamically from the source data of another ListBox.

    • Displaying a file list from external sources inside the ListBox.

    • Populating the ListBox with the output of the Filter() Function.

    These are just a few of the techniques we have previously experimented with using the Access ListBox. For detailed walkthroughs, explore the linked articles below. 

  2. Custom-made Form-Wizard.

  3. Custom-made Report-Wizard.

  4. Open Forms with Hyperlinks in ListBox.

  5. Create a List from Another ListBox.

  6. Dynamic ListBox ComboBox Contents.

  7. Filter Function Output in ListBox.

  8. Filter Function Output in ListBox-2

  9. ListBox and Date Part One.

  10. ListBox and Date Part Two.

The ListView with TreeView Control Demo Image.

The Demo Image View of Form, with TreeView and ListView Controls:

The ListView Demo Form in Design View.

Designing the Form frmListView.

  1. Creating the Form frmListView with TreeView, ListView, and ImageList Controls

    1. Create a New Form

      • Open your database and create a new form.

      • Save the form named frmListView.

    2. Insert a TreeView Control

      • From the ActiveX Controls List, insert a TreeView Control on the left side of the Detail Section.

      • Change its Name property to TreeView0.

      • In the Property Sheet, set:

        • Width: 6.614 cm

        • Height: 9.709 cm

    3. Insert a ListView Control

      • From the ActiveX Controls List, insert a ListView Control to the right side of the TreeView.

      • Change its Name property to ListView0.

      • Set its dimensions:

        • Width: 12.462 cm

        • Height: 9.709 cm

      • Position it close to the TreeView, keeping the top edges aligned.

    4. Insert an ImageList Control

      • From the ActiveX Controls List, insert an ImageList Control on the right side of the ListView.

      • Change its Name property to ImageList3.

    Note on Missing Controls

    If you cannot find TreeView, ListView, or ImageList in the ActiveX controls list, you need to add the Microsoft Windows Common Controls (MSCOMCTL.OCX) reference:

    • Open the VBA Editor (Alt + F11).

    • Go to Tools → References.

    • Locate and attach MSCOMCTL.OCX (Microsoft Windows Common Controls).

    For detailed steps, see the TreeView Control Tutorial (the first link at the top of this page). That guide explains how to register and add MSCOMCTL.OCX to your Access References.

    Reusing the ImageList Control

    If you have already downloaded the Demo Database (from the 4th link at the top):

    1. Open that database.

    2. Locate a form that already contains an ImageList Control.

    3. Open the form in Design View.

    4. Copy the ImageList Control to the Clipboard.

    5. Close the Demo Database and return to your current project.

    6. Open frmListView in Design View and paste the ImageList Control.

    7. Rename it to ImageList3.

    If your copied ImageList already contains preloaded images, skip the next six steps (manually adding images) and continue directly from Step 7.

Adding Images to the ImageList Control

If you inserted the ImageList Control directly from the ActiveX Controls list (rather than copying from the demo database), you can upload your own images. Follow these steps:

  1. Open ImageList Properties

    • Right-click on the ImageList Control.

    • From the shortcut menu, highlight ImageListCtrl_Object and select Properties.

  2. Set the Image Size

    • On the General Tab, select 16 × 16 as the image size option.
      Caution: You cannot change the image size after uploading them.

    • If you later decide on a different size, you must remove all images, select a new resolution, and re-upload the images.

  3. Upload Images

    • Switch to the Images tab.

    • Click the Insert Picture button.

    • Browse and select an image file from your computer.

      • Supported formats include BMP, PNG, JPG, JPEG, and TIFF.

    • The image will be resized to 16 × 16 pixels.

      • Large images may lose quality when reduced.

  4. Assign Index and Key Values

    • Each image is automatically assigned an Index number.

    • Enter a unique Key name for the image in the Key field.

      • Key names are case-sensitive.

      • You can use either the Index number or the Key name when assigning images to TreeView Nodes or ListView Items.

  5. Repeat as Needed

    • Upload as many images as required (typically 4–5 for this project).

    • Once ready, you can copy and reuse this ImageList Control in other projects.

  6. Finalize

    • When you are finished uploading, click OK to close the Properties dialog.

Add an Exit Button

  1. Insert a Command Button at the bottom of the form.

  2. Set its Name property to: cmdExit.

  3. Set its Caption property to: Exit.

Save the Form

  • Save the form as frmListView with all the changes.

Preparing Demo Tables for TreeView–ListView Example

To demonstrate how the ListView Control works together with the TreeView Control, we will create two simple tables based on the Products table from the Northwind sample database.

1. Table: lvCategory

  • This Table holds the category groupings of products, which will be displayed as TreeView Nodes.

  • A new field named BelongsTo (Numeric) has been added.

    • The BelongsTo field establishes the parent-child relationships within the same Table.

    • For example, if a record’s 'BelongsTo' field value is 4 then the record is a child node of the record with ID = 4.

2. Sample Data in lvCategory

  • Four new records were added to the table.

    • The first two records have their BelongsTo value set to 4, making them child nodes of record ID 4.

    • The last two records have their BelongsTo value set to 10, making them child nodes of record ID 10.

  • In the records with ID = 4 and 10, the Product Name/Description indicates that these categories contain multiple item groups.

    • These groups are now split into separate child categories so they can appear under the correct parent node in the TreeView.

3. Table: lvProducts

  • This table holds the product details linked to the categories.

  • The ParentID of the product records have been updated to point to the new sub-category records created in lvCategory.

  • Only one of the original category groups was left unchanged, for specific preference considerations.

4. Relationship Summary

  • lvCategory provides the TreeView nodes (parent and child categories).

  • lvProducts Provides the ListView items linked to each selected category node.

At this stage, the lvCategory table serves as the backbone for TreeView navigation, while the lvProducts table supplies the detailed product records displayed in the ListView.

The lvProducts Table has about 45 records. The Table image, with a few sample records, is given below for reference:

Working with Two Tables.

Before moving forward, let’s take a closer look at the two tables and how they relate to each other within the TreeView and ListView controls.

Up to this point, we have worked with a single table only, where the Node Key, Description, and ParentID fields were stored together. This allowed us to establish parent–child relationships within the same table and display them as nodes in the TreeView.

If you followed the earlier tutorial sessions, you already know how these self-referencing relationships work within one table.

Now, we are moving a step further. We will see how two different tables—lvCategory and lvProducts—are linked together:

  • The TreeView Control will display the category hierarchy from the lvCategory table.

  • The ListView Control will display the related product details from the lvProducts table, based on the currently selected TreeView node.

First, let’s examine the lvCategory table.

  • This table includes a BelongsTo field, which is populated in the last four records.

  • These four records represent child nodes of record IDs 4 and 10 in the lvCategory table.

  • In the TreeView Control, they will appear as child nodes under the corresponding parent nodes:

    • Canned Fruit & Vegetables (ID = 4)

    • Dried Fruits & Nuts (ID = 10)

Next, let’s look at the lvProducts table.

  • This table contains a ParentID field.

  • For each Category Item in the lvCategory table, there is one or more Product Items in the lvProducts table.

  • The ParentID value in the lvProducts  refers directly to the CID (Category ID) in the lvCategory table.

In other words:

  • Every product record in the ListView Control, grouped by the same ParentID, belongs to the corresponding category record in the lvCategory table with the same CID value.

Note: Manually creating both these tables from the original Products table can be time-consuming. If you have been following this tutorial, you may instead download the Demo Database using the link provided at the end of this page.

  • Simply import the lvCategory and lvProducts tables into your current project database.

  • This way, you can build the project directly without reconstructing the tables from scratch.

  • Later, when your project is complete, or if you face some issues, you can always refer back to the Demo Database for validation and troubleshooting.

The Form Module VBA Code.

  1. Open the frmListView form in Design View.

  2. Display the Form Class Module.

  3. Copy and paste the following full VBA Code into the Module and press Ctrl+S to save the Code.

Option Compare Database
Option Explicit

Dim tv As MSComctlLib.TreeView
Dim lvList As MSComctlLib.ListView
Dim imgList As MSComctlLib.ImageList
Const Prfx As String = "X"

Private Sub Form_Load()
Dim db As DAO.Database
Dim tbldef As TableDef

    Set tv = Me.TreeView0.Object
    tv.Nodes.Clear
    
    Set imgList = Me.ImageList3.Object
    
With tv
    .Font.Size = 9
    .Font.Name = "Verdana"
    .ImageList = imgList 'assign preloaded imagelist control
 End With

    Set db = CurrentDb
    Set tbldef = db.TableDefs("lvProducts")
    
    Set lvList = Me.ListView0.Object
    lvList.ColumnHeaders.Clear
    lvList.ListItems.Clear
    lvList.Icons = imgList
    
    'Initialize ListView & Column Headers Property Values
     With lvList
        .ColumnHeaderIcons = imgList
        .Font.Size = 9
        .Font.Name = "Verdana"
        .Font.Bold = False
        .View = lvwReport
        .GridLines = True
     
        'ColumnHeaders.Add() Syntax:
        'lvList.ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
        'Alignment: 0 - Left, 1 - Right, 2 - Center
        .ColumnHeaders.Add 1, , tbldef.Fields(1).Name, 2600, 0, 5
        .ColumnHeaders.Add 2, , tbldef.Fields(3).Name, 2600, 0, 5
        .ColumnHeaders.Add 3, , tbldef.Fields(4).Name, 1440, 1, 5
    End With
    
    Set db = Nothing
    Set tbldef = Nothing

    
   LoadTreeView 'Create TreeView Nodes

End Sub

Private Sub LoadTreeView()
    Dim Nod As MSComctlLib.Node
    Dim firstCatID As Long
    Dim strCategory As String
    Dim strCatKey As String
    Dim strProduct As String
    Dim strPKey As String
    Dim strBelongsTo As String
    Dim strSQL As String
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    
    'Initialize treeview nodes
     tv.Nodes.Clear
     
    'Initialize Listview nodes
    While lvList.ListItems.Count > 0
          lvList.ListItems.Remove (1)
    Wend
    
    strSQL = "SELECT lvCategory.CID, lvCategory.Category, "
    strSQL = strSQL & "lvcategory.BelongsTo FROM lvCategory ORDER BY lvCategory.CID;"
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSQL, dbOpenSnapshot)
    
    If Not rst.BOF And Not rst.EOF Then
        rst.MoveFirst
        firstCatID = rst!CID
    Else
        Exit Sub
    End If
    ' Populate all Records as Rootlevel Nodes
    Do While Not rst.BOF And Not rst.EOF
            strCatKey = Prfx & CStr(rst!CID)
            strCategory = rst!Category
            
            Set Nod = tv.Nodes.Add(, , strCatKey, strCategory, 1, 2)
            Nod.Tag = rst!CID
        rst.MoveNext
    Loop
    
    'In the second pass of the the same set of records
    'Move Child Nodes under their Parent Nodes
    rst.MoveFirst
    Do While Not rst.BOF And Not rst.EOF
        strBelongsTo = Nz(rst!BelongsTo, "")
        If Len(strBelongsTo) > 0 Then
            strCatKey = Prfx & CStr(rst!CID)
            strBelongsTo = Prfx & strBelongsTo
            strCategory = rst!Category
            
            Set tv.Nodes.Item(strCatKey).Parent = tv.Nodes.Item(strBelongsTo)
        End If
        rst.MoveNext
   Loop
    rst.Close
    
    ' Populate ListView Control with Product details
    ' of the first Category Item
    LoadListView firstCatID
    
End Sub


Private Sub LoadListView(ByVal CatID)
    Dim strProduct As String
    Dim strPKey As String
    Dim intCount As Integer
    Dim tmpLItem As MSComctlLib.ListItem
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim strSQL As String
    
    ' Initialize ListView Control
    While lvList.ListItems.Count > 0
        lvList.ListItems.Remove (1)
    Wend
   
     strSQL = "SELECT lvProducts.* FROM lvProducts "
     strSQL = strSQL & "WHERE (lvProducts.ParentID = " & CatID & ") "
     strSQL = strSQL & "ORDER BY lvProducts.[Product Name];"
    
    'Open filtered Products List for selected category
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strSQL, dbOpenSnapshot)
    
    Do While Not rst.BOF And Not rst.EOF
        intCount = intCount + 1
        strProduct = rst![Product Name]
        strPKey = Prfx & CStr(rst!PID)
        
        'List Item Add() Syntax:
        'lvList.ListItems.Add Index,Key,Text,Icon,SmallIcon
        Set tmpLItem = lvList.ListItems.Add(, strPKey, strProduct, , 3) 'first column
            lvList.ForeColor = vbBlue
            
            'List second column sub-item Syntax:
            'tmpLItem.ListSubItems.Add Column - Index, Key, Text, ReportIcon, ToolTipText
            tmpLItem.ListSubItems.Add 1, strPKey & CStr(intCount), Nz(rst![Quantity Per Unit], ""), 6
            
            'List third column sub-item
            tmpLItem.ListSubItems.Add 2, strPKey & CStr(intCount + 1), Format(rst![list Price], "0.00"), 6, "In Local Currency."
        rst.MoveNext
    Loop
    
    Set db = Nothing
    Set rst = Nothing
    
    If intCount > 0 Then lvList.ListItems(1).Selected = True
    
End Sub

Private Sub TreeView0_NodeClick(ByVal Node As Object)
Dim Cat_ID As String
Cat_ID = Node.Tag

LoadListView Cat_ID

End Sub

Private Sub ListView0_Click()
Dim lvKey As String, lvLong As Long
Dim Criterion As String

lvKey = lvList.SelectedItem.Key
lvLong = Val(Mid(lvKey, 2))

DoCmd.OpenForm "ProductDetails", , , , , , lvLong

End Sub
Private Sub cmdExit_Click()
    DoCmd.Close
End Sub

Let’s review the code and understand its functionality.

In the global declaration area, the following object variables are declared:

  • TreeView Object (tv)

  • ListView Object (lvList)

  • ImageList Object (imgList)

Additionally, a constant named Prfx is declared with the value "X", which is used as the prefix for Node Keys.

When the form frmListView is opened, the Form_Load() event procedure executes.

  • Within this procedure, the database object (db) and TableDef object variable (tbldef) are declared.

  • The TreeView0 control on the form is assigned to the variable tv.

  • The statement tv.Nodes.Clear initializes the TreeView control instance by clearing any existing nodes.

  • Next, the imgList variable is initialized with the ImageList3 control on the form.

TreeView Control Display Font and ImageList Properties.

The following statements configure the TreeView control’s font settings (Font Name and Font Size) and assign its ImageList property to the imgList object. This allows the TreeView nodes to display images using either the Image Key names or the Image Index numbers.

With tv
    .Font.Size = 9
    .Font.Name = "Verdana"
    .ImageList = imgList 'assign preloaded imagelist control
 End With

The ListView Control Property Settings and Column Headers.

After that, the following Code segment initializes the ListView Control and assigns its Property values.

    Set db = CurrentDb
    Set tbldef = db.TableDefs("lvProducts")
    
    Set lvList = Me.ListView0.Object
    lvList.ColumnHeaders.Clear
    lvList.ListItems.Clear
    lvList.Icons = imgList
    
    'Initialize ListView & Column Headers Property Values
     With lvList
        .ColumnHeaderIcons = imgList
        .Font.Size = 9
        .Font.Name = "Verdana"
        .Font.Bold = False
        .View = lvwReport
        .GridLines = True
        
        'ColumnHeaders.Add() Syntax:
        'lvList.ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
        'Alignment: 0 - Left, 1 - Right, 2 - Center
        .ColumnHeaders.Add , , tbldef.Fields(1).Name, 2600, 0, 5
        .ColumnHeaders.Add , , tbldef.Fields(3).Name, 2600, 0, 5
        .ColumnHeaders.Add , , tbldef.Fields(4).Name, 1440, 1, 5
    End With
    
    Set db = Nothing
    Set tbldef = Nothing

The variable tbldef is assigned the table definition of the lvProducts table. Its field names are the ListView column headers, ensuring that each column header corresponds to a table field.

Since column headers can also display icons, the imgList Object is assigned to the lvList.ColumnHeaderIcons property.

Next, the customized font name, size, and style for the ListView Control if the default settings are not suitable.

The overall appearance of the ListView is determined by its View property. In this project, we use lvwReport (value = 3), which provides the most features—column headers, grid lines, and image support. You may also experiment with other values (0, 1, or 2) to explore the different display styles.

We selected three fields from the lvProducts table—Product Name, Quantity Per Unit, and List Price—to display in three separate columns of the ListView control.

The Column Width is specified in pixels. The Alignment property accepts values from 0 to 2, which defines text alignment within each column:

  • 0 – Left align

  • 1 – Right align

  • 2 – Center align

To define the column headers, the lvList.ColumnHeaders.Add() is used with the following syntax:

Object.ColumnHeaders.Add Index, Key, Text, ColumnWidth, Alignment, Icon

Using this method, we added all three column headers—Product Name, Quantity Per Unit, and List Price—before inserting any data into the ListView control. This step is performed in the Form_Load() event procedure, rather than during item population, to ensure the structure is ready in advance.

Next, the Subroutine LoadTreeView()  is called to create the TreeView nodes. As discussed in earlier tutorials, this task is handled in two stages for clarity and maintainability.

After declaring the required variables, the TreeView and ListView controls are initialized. Immediately upon opening the lvCategory recordset, the first record’s CID (Category ID) value is stored in the firstCatID variable for later reference.

Finally, all records from the lvCategory table are added to the TreeView control as root-level nodes.

In the second pass through the same set of records, the code evaluates the BelongsTo field.

  • If BelongsTo is empty, the node remains at the root level.

  • If a value exists, that value represents the ParentID of another root-level node. Using this ParentID, the current node is placed under its corresponding parent as a child node.

This two-step approach to populating the TreeView ensures proper hierarchical structure. I explained this concept in detail in an earlier episode, and we confirmed its behavior through hands-on experiments in the previous tutorial session.

After closing the recordset object, the procedure calls the LoadListView(ByVal CatID) subroutine. The CID value of the first category record—saved earlier in the firstCatID variable—is passed as a parameter.

Inside the LoadListView Subroutine, the 'CID' value is used in the strSQL filter string to retrieve only those product records that belong to the selected category. In this way, the ListView displays only the products related to the current category.

From the filtered product records, we use only four fields: PID, Product Name, Quantity Per Unit, and List Price. The PID field serves as the key value for each item, but is not displayed in the ListView.

To display the other three fields, the ColumnHeaders.Add()  is called three times, once for each column header.

Note:
In these statements, we have not specified a Key parameter for the column headers. Instead, the system automatically assigns an Index value. Since we do not plan to manipulate the column headers after they are created, the index is sufficient. However, when loading product records into the ListView, we must ensure that the field values are inserted in the same sequence as the column headers.

Populating the ListView Control with Product Values in Columns.

To display product records in the ListView control, we use two sets of Add() methods:

  1. ListItems.Add() – for the first column value.

  2. ListSubItems.Add() – for all subsequent column values.

Since the ListView requires a unique key for each item, we use the PID field along with a counter variable (intCount). The counter is incremented in each Do While...Loop cycle, and its current value is appended to the PID to guarantee uniqueness in the ListSubItems.Add() method.

Syntax: Adding the first column

lvList.ListItems.Add(Index, Key, Text, Icon, SmallIcon)

  • Index – Position of the item in the ListView.

  • Key – Unique identifier (we use PID & intCount).

  • Text – The display value for the first column (e.g., Product Name).

  • Icon / SmallIcon – Optional parameters for assigning images.

‘lvList.ListItems.Add Index,Key,Text,Icon,SmallIcon

Set tmpLItem = lvList.ListItems.Add(, strPKey, strProduct, , 3)

The ListItems.Add() The ListView works very much like the Nodes.Add() method in the TreeView control.

We first declare an ListItem object variable (tmpLItem) to hold a reference to the item returned by ListItems.Add(). This reference is to attach sub-items to that row.

Adding SubItems

The ListSubItems.Add() It is slightly different in syntax. Each sub-item also requires a unique key, so we use the product key (strPKey) combined with the loop counter (intCount).

For example:

  • First sub-item → Key = strPKey & CStr(intCount)

  • Second sub-item → Key = strPKey & CStr(intCount + 1)

Syntax Example.

' Add first column (Product Name) Set tmpLItem = lvList.ListItems.Add(, strPKey, rs!ProductName) ' Add second column (Quantity Per Unit) tmpLItem.ListSubItems.Add , strPKey & CStr(intCount), rs!QtyPerUnit ' Add third column (List Price) tmpLItem.ListSubItems.Add , strPKey & CStr(intCount + 1), rs!ListPrice

Here:

  • tmpLItem anchors the row.

  • Each ListSubItems.Add() attaches a value to the same row, ensuring the fields sequence matches the column header sequence.

  • The counter (intCount) keeps sub-item keys unique, avoiding conflicts.

The ListSubItems.Add() supports five parameters:

tmpLItem.ListSubItems.Add Index, Key, Text, ReportIcon, ToolTipText

In our example:

tmpLItem.ListSubItems.Add 2, strPKey & CStr(intCount + 1), _ Format(rst![List Price], "0.00"), 6, "In Local Currency."
  • Index → Position of the sub-item (here, 2)

  • Key → Unique identifier (strPKey & CStr(intCount + 1))

  • Text → Display text (List Price formatted as "0.00")

  • ReportIcon → Image index from the assigned imgList (here, 6)

  • ToolTipText → Tooltip shown when hovering over the sub-item (used here only for the last column).

Important Note

All column-related features (headers, alignment, icons, tooltips, etc.) work only when the ListView View Property is set to 3 (lvwReport).

  • In other views (0, 1, or 2) Only the first column is displayed; sub-items and their settings are ignored.

The tooltip text appears when the mouse pointer hovers over the last column.

For all three columns (the ListItem and its ListSubItems), The Add() uses the same record’s PID as the base key. However, since each column of the same record requires a unique key value, the counter variable intCount is incremented and concatenated with the PID. This ensures every column entry has a distinct key.

This approach displays all product records related to the selected category in the ListView control.

Separate Form to Display Full Product Record Details.

Because the lvProducts table contains more fields than can be accommodated within the ListView’s width, the ListView ItemClick event is used to open a separate form, ProductDetails, where the complete record information is displayed.

The image below shows the form with all details of the selected product:

The ListView0_Click() Event Procedure.

Private Sub ListView0_Click()
Dim lvKey As String, lvLong As Long
Dim Criterion As String

lvKey = lvList.SelectedItem.Key
lvLong = Val(Mid(lvKey, 2))

DoCmd.OpenForm "ProductDetails", , , , , , lvLong

End Sub

Would you like me to also expand this into a short step explanation (1–2 lines) showing how Access uses OpenArgs inside Form_Load to retrieve the record? That would make the tutorial flow more practical for readers.

The ProductDetails Form.

In the Form_Open() event procedure, the value passed through OpenArgs builds a filter criterion. This ensures that the selected product record is retrieved and displayed on the ProductDetails form.

The form’s module code is as follows:

Option Compare Database
Option Explicit

Private Sub cmdClose_Click()
DoCmd.Close
End Sub

Private Sub Form_Open(Cancel As Integer)
Dim lngID As Long
lngID = Nz(Me.OpenArgs, 0)
If lngID > 0 Then
    Me.Filter = "id = " & lngID
    Me.FilterOn = True
End If
End Sub

Private Sub Form_Unload(Cancel As Integer)
With Me
    .Filter = ""
    .FilterOn = False
End With
End Sub

The ProductDetails form retrieves its source data from the filtered recordset, using the PID (Product ID) value passed through OpenArgs. This ensures that only the selected product details are displayed.

The original Products table is imported from the Northwind.accdb sample database and renamed as ProductsNew. 

I hope you enjoyed working through this ListView control project. More tutorials with advanced ListView features are coming soon.

Download the demo database from the link below, and happy List Viewing!

Demo Database Download.


  1. ROUNDDOWN Function of Excel
  2. Call Function From MouseMove Event
  3. Date2Text and Text2Date Function
  4. WithEvents MS Access Class Module Tutorial
  5. WithEvents and Defining Your Own Events
  6. withevents Button Combo List TextBox Tab
Share:

Rearrange TreeView Nodes by Drag and Drop

Rearranging TreeView Nodes.

I hope you found last week’s tutorial on the ImageCombo Control useful in your Microsoft Access projects. With the TreeView-style ImageCombo, we created a compact yet versatile drop-down menu that supports multiple options and needs only very little space on a form.

In an earlier session, we explored how to add new Nodes at specific positions in the hierarchy, or delete and reinsert Nodes to relocate them on the TreeView control.

That method required creating a new record in the source table (for new Nodes) or deleting and recreating records (to move existing Nodes), ensuring the changes were stored permanently. Using these Add/Delete functions, we could build or restructure the Node hierarchy as needed.

However, when it comes to rearranging Nodes, there’s a more efficient approach than repeatedly deleting and recreating them: simply drag the Node from its current position and drop it into its new location within the TreeView control. That’s exactly what we’ll be learning in this episode.

This method's advantage is its simplicity. Instead of complex record manipulations, we only need to update the ParentID field of the affected records. This single change makes the new Node arrangement permanent.

The Topics Covered so far in Earlier Sessions.

  1. Microsoft TreeView Control Tutorial
  2. Creating an Access Menu with a TreeView Control
  3. Assigning Images to TreeView Control
  4. Assigning Images to TreeView Control-2
  5. TreeView Control Check-Mark Add, Delete Nodes
  6. TreeView ImageCombo Drop-down Access Menu

However, while this method is simpler, it poses a few challenges and limitations that we should be aware of. We’ll explore these issues in detail later in this session, along with some techniques to handle them effectively.

Demo Data Table and Form.

For this exercise, we need a Table and a Form. Fortunately, we already have a suitable table named Sample, which we created in an earlier tutorial session. If you have previously downloaded the Demo Database from the second link provided above, you can continue using that database for this session as well. We will make use of the following objects from that database for our drag-and-drop experiments:

  • Table: Sample
  • Form: frmSample

The TreeView Control Image on frmSample with demo data is given below for reference:

You can download the Demo Database (ProjectMenu.zip) from the second link provided above, then extract the file to obtain ProjectMenu.accdb.

New Form for Drag and Drop Trial Runs.

  1. Open the ProjectMenu.accdb database.

  2. First, create a copy of the Sample table and name it Sample_bk. The backup copy ensures that the original data is safe for later use. During our drag-and-drop experiments, the ParentID field values in the Sample table will be updated, but we will need the original data intact afterward.

  3. Next, create a new form and name it frmDragDrop.

  4. Once you have finished designing the form, it will resemble the illustration shown below.


  1. Insert the TreeView Control

    • From the ActiveX Controls list, insert a TreeView Control onto the form.

    • Leave enough space above the control to accommodate two command buttons and a heading label.

    • Drag the sizing handle at the bottom-right corner to enlarge the TreeView Control so that all the nodes are clearly visible without scrolling.

    • Change the Name property of the TreeView control to TreeView0.

  2. Add the Command Buttons

    • Insert a Command Button above the left edge of the TreeView control.

      • Set its Name property to cmdExpand.

      • Set its Caption property to Expand All.

    • Insert another Command Button above the right edge of the TreeView control.

      • Set its Name property to cmdCollapse.

      • Set its Caption property to Collapse All.

  3. Add the Heading Label

    • Insert a Label Control above the command buttons.

    • Make it wide enough to display the heading as shown in the reference image.

    • Increase the Font Size to 14 for better visibility.

  4. Skip the ImageList for Now

    • We will ignore the ImageList Control for now.

    • The code lines that modify the Node’s ImageList index numbers have been commented out.

    • Later, you can import the ImageList Control along with manually uploaded images from our earlier Tutorial Demo Database (see the 4th Link Page mentioned previously).

    • This will allow you to display images on the nodes.

    • During the Node drag-and-drop action, node positions are changed. At this point, the Node images should also be updated to reflect their new positions (whether they are root-level nodes or child nodes).

    Drag-Drop Form Module Code.

  5. Open the VBA Code Module of the form frmDragDrop.
    Copy and paste the following VBA code (this is only the first half of the form’s module code) into the frmDragDrop Form’s Class Module, and then save the form:

    Option Compare Database
    Option Explicit
    
    Dim tv As MSComctlLib.TreeView
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    Dim imgListObj As MSComctlLib.ImageList
    Const KeyPrfx As String = "X"
    
    Private Sub Form_Open(Cancel As Integer)
    Set tv = Me.TreeView0.Object
    
    'Set imgListObj = Me.ImageList1.Object
    'tv.ImageList = imgListObj
    
    LoadTreeView
    
    End Sub
    
    Sub LoadTreeView()
    Dim strKey As String
    Dim strPKey As String
    Dim strText As String
    Dim strsQL As String
    
    strsQL = "SELECT * FROM Sample ORDER BY ID"
    
    Set db = CurrentDb
    Set rst = db.OpenRecordset(strsQL, dbOpenDynaset)
        
    tv.Nodes.Clear
    
    'Add all Items are added as Root Nodes
    Do While Not rst.BOF And Not rst.EOF
        strKey = KeyPrfx & CStr(rst!ID)
        strText = rst!desc
        tv.Nodes.Add , , strKey, strText
        
        'With tv.Nodes.Item(strKey)
        '    .Image = 1
        '    .SelectedImage = 4
        'End With
    
        rst.MoveNext
    Loop
    
    'Prepare to update the Parent-Key of Nodes
    'wherever applicable to move and position the Child Nodes
    strPKey = ""
    rst.MoveFirst
    Do While Not rst.EOF
        strPKey = Nz(rst!parentid, "")
        
        If Len(strPKey) > 0 Then
            strPKey = KeyPrfx & strPKey
            strKey = KeyPrfx & CStr(rst!ID)
            strText = rst!desc
            
            'Move the Child Node under it's Parent-Node
            Set tv.Nodes.Item(strKey).Parent = tv.Nodes.Item(strPKey)
            
    'Update Image and SelectedImage Properties
    'with ImageList Index numbers
            'With tv.Nodes.Item(strKey)
            '    .Image = 2
            '    .SelectedImage = 3
            'End With
    
        End If
        rst.MoveNext
    Loop
    
    rst.Close
    Set rst = Nothing
    Set db = Nothing
    
    End Sub
    
    
    Private Sub TreeView0_NodeClick(ByVal Node As Object)
    Dim SelectionNode As MSComctlLib.Node
        
    'Ensure that the clicked node equals the selected node in the tree
    If Not Node Is Nothing Then
        Set SelectionNode = Node
           If SelectionNode.Expanded = True Then
                SelectionNode.Expanded = False
            Else
                SelectionNode.Expanded = True
            End If
    End If
    End Sub
    
    Private Sub cmdCollapse_Click()
    Dim tmpnod As MSComctlLib.Node
    For Each tmpnod In tv.Nodes
        If tmpnod.Expanded = True Then
            tmpnod.Expanded = False
        End If
    Next
    
    End Sub
    
    Private Sub cmdExpand_Click()
    Dim tmpnod As MSComctlLib.Node
    For Each tmpnod In tv.Nodes
        If tmpnod.Expanded = False Then
            tmpnod.Expanded = True
        End If
    Next
    
    End Sub

    If you have followed the earlier episodes, most of the above code should look familiar. The main difference lies in the LoadTreeView() subroutine, which now works slightly differently.

    In this version, populating the TreeView nodes is done in two steps:

    1. First pass:
      All records from the Sample table are loaded as root-level nodes in the TreeView control. Each node uses the ID field as its Key.

    2. Second pass:
      The same records are read again, this time checking for values in the ParentID field.

      • If the ParentID field is empty, the node remains as a root-level node.

      • If the ParentID field contains a value, the code locates the node whose Key matches this ParentID, and then reassigns the current node as its child node (updating the [Relative] parameter of the Add() method accordingly).

    At first glance, this two-step population may look redundant, but there is a very specific reason behind it. We will revisit this later in the session, and the advantage will be clear without needing much explanation.

    On the form design, I have included an ImageList control. You may:

    • Insert the ImageList ActiveX control and upload a few images manually from your disk, or

    • Copy and paste the ImageList control (with preloaded images) from one of the earlier demo databases.

    Make sure the control is named ImageList1. Otherwise, you will need to update the control name in the code.

    After adding the ImageList, enable the commented-out lines in the Form_Open() event procedure by removing the leading apostrophes:

    'Set imgListObj = Me.ImageList1.Object 'tv.ImageList = imgListObj

    Similarly, in the TreeView0_OLEDragDrop() subroutine (found in the second part of the VBA code), remove the comment symbols from the lines that update the Image Index parameters. With these changes, images will appear alongside the TreeView nodes.

    If you already have your own ImageList control with uploaded images, adjust the image index in the code to decide which images should appear on each node.

    The TreeView0_NodeClick() event procedure expands the currently selected node if its child nodes are collapsed; otherwise, it collapses them. Normally, this expand/collapse action can be done by clicking the [+] or [–] symbol next to the node, but here it is handled programmatically for more control.

    The cmdExpand_Click() and cmdCollapse_Click() subroutines expand all nodes and collapse all nodes, respectively.

    When you run the code, the form will display as shown in the Form View image below:

    You may save the frmDragDrop Form and open it in Normal View.  If everything went well, then you will see the screen above.  Try out the Expand All and Collapse All Command Buttons and check whether they are working too.  If not, then re-check whether the following settings are correct or not:

    i)  The TreeView Control’s Name is: TreeView0

    ii)  Display the Property Sheet of the Expand All Command Button and select [Event Procedure] in the On Click Event Property.

    iii) Ensure that the same setting is intact for the Collapse All Command Button also. 

    iv) Click on a Node, having Child Nodes to see whether they collapse or expand on repeated clicks.

     v) If the ImageList Control is placed on the Form, then its name must be ImageList1.

    Let us proceed with the second part of the VBA Code that implements the drag-and-drop events.

    Second Half of the VBA Code.

    Copy the following Second Part of the VBA code to the frmDragDrop Form Module that implements the drag-and-drop action, and paste it below the existing Code:

    Private Sub TreeView0_OLEStartDrag(Data As Object, AllowedEffects As Long)
        Set Me.TreeView0.SelectedItem = Nothing
    End Sub
    
    
    Private Sub TreeView0_OLEDragOver(Data As Object, _
                                    Effect As Long, _
                                    Button As Integer, _
                                    Shift As Integer, _
                                    x As Single, _
                                    y As Single, _
                                    State As Integer)
        
        Dim SelectedNode As MSComctlLib.Node
        Dim nodOver As MSComctlLib.Node
        
        If tv.SelectedItem Is Nothing Then
            'Select a node if one is not selected
            Set SelectedNode = tv.HitTest(x, y)
            If Not SelectedNode Is Nothing Then
                SelectedNode.Selected = True
            End If
        Else
            If tv.HitTest(x, y) Is Nothing Then
            'do nothing
            Else
                'Highlight the node the mouse is over
                Set nodOver = tv.HitTest(x, y)
                Set tv.DropHighlight = nodOver
            End If
        End If
    
    End Sub
    
    
    Private Sub TreeView0_OLEDragDrop(Data As Object, _
                                        Effect As Long, _
                                        Button As Integer, _
                                        Shift As Integer, _
                                        x As Single, _
                                        y As Single)
    
        Dim sourceNode As MSComctlLib.Node
        Dim SourceParentNode As MSComctlLib.Node
        Dim targetNode As MSComctlLib.Node
        
        Dim tmpRootNode As MSComctlLib.Node
        Dim strtmpNodKey As String
        Dim ChildNode As MSComctlLib.Node
        
        Dim strSPKey As String
        Dim strTargetKey As String
        
        Dim strsQL As String
        Dim intKey As Integer
        Dim intPKey As Integer
        
        On Error Resume Next
        
        Select Case Screen.ActiveControl.Name
                
               Case TreeView0.Name
                    Set sourceNode = tv.SelectedItem
                
        End Select
        
        'Get Source Parent Node & Target Node Reference
        Set SourceParentNode = sourceNode.Parent
        Set targetNode = tv.HitTest(x, y)
                
        'If any errors then exit
        If Err <> 0 Then
            MsgBox Err & " : " & Err.Description, vbInformation + vbCritical, "OLEDragDrop()"
            Err.Clear
            Exit Sub
        Else
            On Error GoTo 0
        End If
        
    
        'Get/define Source parent Node Key to compare it with Target Node Key
        If SourceParentNode Is Nothing Then
            strSPKey = "Empty"
        Else
            strSPKey = SourceParentNode.Key
        End If
        
        'Check the Target Node/Location and define the Key
         Select Case True
            Case targetNode Is Nothing
                strTargetKey = "Empty"
            
            Case targetNode.Key = ""
                strTargetKey = "Empty"
                Set targetNode = Nothing
            Case Else
                strTargetKey = targetNode.Key
         End Select
        
        'Make sure the Target Node is not the source Node's own parent
        If strTargetKey = strSPKey Then Exit Sub
        
        'Track User's Node move action, check for error.
        On Error Resume Next
        
        If targetNode Is Nothing Then
            
            'If target Node is Nothing (the Node dropped in the empty area),
            'then the Node must be moved to the Root-level
            'save the original sourceNode.Key
            strtmpNodKey = sourceNode.Key
            
            'Modify the source Node Key, with addition of some text, say 'Empty', like 'X5Empty'
            'So that a temporary Node can be created with the original source Node key.
            'Note: Two Nodes with the same Key cannot remain in memory at the same time.
            'The Source Node with key 'X5Empty' deleted later,
            'temporary Node takes it's droped location.
            sourceNode.Key = sourceNode.Key & strTargetKey
    
            'Create the temporary Root Node, with original sourceNode Key
            Set tmpRootNode = tv.Nodes.Add(, , strtmpNodKey, sourceNode.Text)
            
            'define the Root Node image indexes
            'With tmpRootNode
            '    .Image = 1
            '    .SelectedImage = 4
            'End With
            
            'Move all child Nodes from SourceNode,if any,
            'as tmpRootNode's Children
            Do Until sourceNode.Children = 0
                Set sourceNode.Child.Parent = tmpRootNode
                
                'modify Node image indexes
                'With sourceNode
                '    .Image = 2
                '    .SelectedImage = 3
                'End With
            Loop
    
            'Delete the Source Node with modified Key from TreeView
            tv.Nodes.Remove sourceNode.Index
            
            'Move the tmpRootNode with original Key
            'to the dropped location on TreeView
            Set sourceNode = tmpRootNode
        Else
            'Move the sourceNode under targetNode as child
            Set sourceNode.Parent = targetNode
            
            'modify Node image indexes
            'With sourceNode
            '    .Image = 2
            '    .SelectedImage = 3
            'End With
        End If
        
        'Notify, if there was an Error then Exit, else Update PrentID of related Record.
        If Err <> 0 Then
            MsgBox Err & " : " & "Unable to move:" & vbCrLf & Err.Description, vbInformation + vbCritical, "DragDrop2()"
            Exit Sub
        Else
            'Build and execute the SQL statement to update the record
            If targetNode Is Nothing Then
                intKey = Val(Mid(sourceNode.Key, 2))
                strsQL = "UPDATE Sample SET ParentID = Null" & _
                         " WHERE ID = " & intKey
            Else
                intKey = Val(Mid(sourceNode.Key, 2))
                intPKey = Val(Mid(targetNode.Key, 2))
                
                strsQL = "UPDATE sample SET ParentID = " & intPKey & _
                         " WHERE ID = " & intKey
            End If
            
            'Modify the table records
            CurrentDb.Execute strsQL, dbFailOnError
            
            'If an error raised then refresh TreeView and exit
            If Err <> 0 Then
                MsgBox Err & " : " & Err.Description
                LoadTreeView 'Refresh/display TreeView without changes
            Else
                'Sort Nodes
                If sourceNode.Parent Is Nothing Then
                    sourceNode.Root.Sorted = True
                Else
                    sourceNode.Parent.Sorted = True
                End If
                
                tv.Nodes(sourceNode.Key).Selected = True
            End If
        End If
        On Error GoTo 0
    
    End Sub
    
    Private Sub TreeView0_OLECompleteDrag(Effect As Long)
    
        'Turn off the drophighlight
        Set tv.DropHighlight = Nothing
    
    End Sub
    
    Private Sub Form_Close()
    
    Set tv = Nothing
    End Sub

  6. For the drag-and-drop action, four event procedures are executed automatically. These handle the different stages of the process—when you begin dragging a node, when the dragged node is moved over other nodes (highlighting them as potential targets), and finally, when it is dropped either on another node or onto the empty root-level area.

    The Main Subroutines of the Code.

    The drag-and-drop operation in the TreeView control is managed through four key event procedures:

    • TreeView0_OLEStartDrag() – Initializes the drag process by setting the selected item and resetting the Node to Nothing.

    • TreeView0_OLEDragOver() – Functions like the MouseMove event; it highlights the node as the dragged item is moved over potential target nodes.

    • TreeView0_OLEDragDrop() – Handles the main task: performs the necessary checks, positions the node(s) at the drop location, and updates the related record in the base table.

    • TreeView0_OLECompleteDrag() – Completes the action by resetting the DropHighlight Property to Nothing.


Technically, the entire drag-and-drop process could be managed with the TreeView0_OLEDragDrop() procedure alone. However, without the supporting routines, nodes will not be visually highlighted when the dragged item passes over them. The only indicator would be the mouse pointer, which changes to display a small second arrow, as shown in the sample image above.

With that in mind, let us now focus on this subroutine and review its code in detail. At the beginning of the procedure, we declare the required string variables for the nodes, along with other supporting variables.

Rather than analyzing the code line by line here, note that each section is already documented with inline comments, making it easier for you to follow and understand the logic as you go through the code yourself.

The Sequence of Drag-and-Drop Events

Let us first understand the sequence of events: the user selects a node, drags it over other nodes on the way to its final destination, and finally drops it either on a target node or in the empty space of the TreeView control to make it a root-level node.

As you drag a node over another node’s text, the text becomes highlighted, indicating your current position. Once you move away, the highlight disappears. This visual feedback continues until you reach the target node. The TreeView0_OLEDragOver() subroutine manages this highlighting behavior.

When a node is finally dropped, the TreeView0_OLEDragDrop() subroutine takes over. At this stage, the user’s intention must be interpreted, and the appropriate action taken. To move the node correctly, the following information must be captured and analyzed.

The Important Information to Keep Track Of.

To correctly process a drag-and-drop action, the following details must be identified and analyzed:

  • Source Node details: reference to the node, its key, ParentID value, and any child nodes.

  • Target Node or location: reference and key of the node on which the source node is dropped.

  • Drop on empty TreeView area: if the target is not another node but the blank area of the TreeView, the source node is moved to the root level.

  • Drop on another node: the target node becomes the new parent of the source node.

  • Child nodes: if the source node has children, they are moved together with their parent node.

Special cases where no action is taken:

  • Dropping a node onto its own parent.

    • Example: dragging the TextBox node and dropping it onto Controls, or dragging Controls onto its parent Form. These attempts simply place the node back in its current position, so the action is ignored.

  • Dragging a root-level node and dropping it onto the empty TreeView area. Since it is already a root node, no action is needed.

For all valid moves, the corresponding record in the Sample table must be updated by setting its ParentID field to reflect the new hierarchy.

Node Drop in the Root-level Empty Area.

In case #3 (dropping a node onto the empty TreeView area), we face a technical issue:

A new root-level node must be created with the same key as the source node. However, duplicate keys are not allowed in the TreeView hierarchy. This is where the procedure gets slightly confusing.

The workaround is as follows:

  1. Rename the source node’s key temporarily

    • Append a suffix to the key (e.g., change X5 → X5Empty) so that the original key (X5) becomes available.

    • This prevents a duplicate key conflict.

  2. Create a temporary node with the original key

    • Insert a new node using the original key (X5) at the root level.

  3. Reassign child nodes (if any)

    • Move all child nodes from the renamed source node (X5Empty) to the new temporary node (X5).

  4. Delete the renamed source node

    • Remove the source node (X5Empty) from the TreeView control.

    • Note: this deletion only affects the TreeView; the related record in the Sample table remains untouched.

  5. Promote the new node to the root level

    • The temporary node (X5) — now carrying its children — is placed at the root level.

  6. Update the table

    • Set the ParentID field of the corresponding record to a zero-length string (""), marking it as a root-level node in the database.


This sequence ensures:

  • No duplicate key errors in the TreeView.

  • All child nodes remain intact with their parent.

  • The database correctly reflects the change in hierarchy.

Self-Experiments of Drag and Drop.

You can try out a few drag-and-drop experiments yourself to see this in action. Select a node, hold down the left mouse button, and drag it to a new location—either onto another node or into the empty area of the TreeView control.

  • As you drag the node over another node’s text, the target node becomes highlighted, and the highlight disappears once you move away.

  • When you release the mouse button, the dragged node is placed in its new position.

  • You can repeat this process with a single node or a node with its children, and the entire branch will move together.

Behind the scenes, each move updates the record in the table: the ParentID field is assigned the Key value (ID) of the new Parent Node’s record. If the node is dropped in the empty area, the ParentID is set to a zero-length string to mark it as a root-level node.

Why Two-Step Node Populating Procedure?

Now, let’s return to the LoadTreeView() subroutine and take a closer look at the two-step process we used to populate the TreeView control with all nodes.

  1. First pass: All records from the Sample table are added as root-level nodes, using the ID field value as the node key.

  2. Second pass:

    • If the ParentID field is empty, the node remains as a root-level node.

    • If the record contains a ParentID value, the node is correctly positioned under its corresponding parent node.

At this point, you may wonder: Why is this two-step process necessary?

Rather than explaining in detail, we’ll answer this through a quick experiment. You may already have tried a few drag-and-drop operations and rearranged nodes, which also updated their corresponding ParentID values in the table. To ensure our demo starts with clean data, we need to restore the table to its original state.

Fortunately, we already created a backup copy earlier, named Sample_bk. Here’s what to do:

  • Delete the current Sample table.

  • Create a fresh copy of Sample_bk and rename it as Sample.

  • Open the table to view the records and their ParentID values.

A sample image of the table is shown below:

The ID field values in the Sample table are AutoNumbers. They are always sequential and unique.

When adding child nodes to the TreeView control, we follow one fundamental principle:

The Simple Child Node Rule

A record’s ParentID value (the parent key) assumes that a parent node with the same Node-Key (ID) already exists in the TreeView control.

Let’s look at a couple of examples from the table image above:

  • Record 3:

    • ID = 3

    • ParentID = 2
      This means the record with ID = 2 must already exist in the TreeView before record 3 can be added as its child node.

  • Record 21:

    • ID = 21

    • ParentID = 12
      Even though record 21 appears much later in the table, its parent node (ID = 12) must still be present in the TreeView before it can be added as a child.

In both cases, the program assumes that by the time a record with a ParentID value is processed, the parent record (ID = ParentID) has already been added as a node in the earlier cycle of populating the TreeView.

Justifying the Two-Step Procedure.

Now let’s try out some drag-and-drop trial runs.

Before we begin, recall that we originally had a form named frmSample (from our first tutorial session). In that form, all TreeView nodes were loaded in a single pass. We’ve followed the same approach so far, but from this point onwards, we’ll adopt the new method.

  1. Open frmSample

    • This form still uses the old loading method.

    • Observe how the TreeView nodes are displayed with the Sample table records.

  2. Close frmSample After you’re done viewing the nodes.

  3. Open frmDragDrop

    • This form is prepared for testing drag-and-drop functionality.

    • Select the node with the Node-Text “Table”.

    • Click and hold the left mouse button, drag it, and drop it onto the node with the Node-Text “Form.”

    When you do this, the Table node and all of its children (its immediate child node Fields and the Fields’ own children) are moved under the Form node as child nodes.

  4. Close frmDragDrop and reopen it.

    • You will notice that the nodes are correctly positioned where you dropped them earlier, as shown in the sample image below.


This step-by-step trial shows that the drag-and-drop action not only repositions nodes visually but also updates their relationships in the underlying Sample table so that the new hierarchy persists.

  1. Now, close the form frmDragDrop.

  2. Open the form frmSample.

    • Instead of displaying the TreeView nodes, you will be greeted with an error message:

      Element Not Found
      Error Number: 35601

  3. Click the Debug command button in the error dialog.

    • This takes you to the highlighted code line where the error occurred.

    • If you hover the mouse over the parameters in the Add() method:

      • nodKey shows X3

      • ParentKey shows X7

  4. From these values, we can infer:

    • The program is currently processing the record with ID = 3.

    • It is attempting to make this record a child node of the record with ID = 7.

    • However, node ID = 7 has not yet been added to the TreeView in this pass, which causes the Element Not Found error.

  5. Press the F5 key to show the error dialog again, and then click End to stop the program.

    • This will return you to the database window.

    • Close the form frmSample.

  6. Now, open the Sample table to review the arrangement of the ParentID values after our drag-and-drop action.

    • You will see the updated records reflecting the change.

    • Notice the highlighted record where the ParentID = 7, showing its parent record’s position.

    • This is the record that triggered the error when the TreeView tried to rebuild the hierarchy frmSample.


  7. This illustrates why our two-step loading method LoadTreeView() (root-level first, then re-parenting in the second pass) is essential. It ensures that when a child node is being added, its parent already exists in the TreeView control.

    Right-click to open the Large Image in a New Window.

    Following the normal node-population procedure, we arrive at the third record.

    • This record has a ParentID value of 7, which means the node with ID = 7 must already exist in the TreeView control.

    • However, since the node with ID = 7 has not yet been added, the program attempts to reference a non-existent node, which immediately triggers the error.

    You might think that simply sorting the records  ParentID before loading them could resolve the issue. Unfortunately, even if we rearrange the records this way, the problem remains. The new order would look like the sample image shown below.


    This sets up the explanation for why a two-pass method is necessary—because sorting alone cannot guarantee that every parent node exists before its children are added.

    When we look further into the recordset, we find another case where the expected Parent Node is not yet available in the TreeView. This reinforces the fact that relying on a single-pass load (or even sorting) is not enough.

    This is exactly why our two-step TreeView Node loading approach is necessary. It works consistently for both the initial load and for cases where Nodes have been rearranged by drag-and-drop.

    Step 1 – Populate all records as Root-level Nodes

    • Each record is added to the TreeView as a root-level Node.

    • The record’s ID field value is used as the Node-Key.

    • At this point, all Nodes exist in the TreeView, even though the hierarchy is not yet correct.

    With this, we guarantee that no matter what ParentID a record refers to, the corresponding Node already exists in the TreeView.

    Step 2 – Reorganize Nodes under their correct parents

    • Loop through the same set of records again.

    • If the ParentID field is empty, the Node remains at the root level.

    • Otherwise, the Node is reassigned as a child of its Parent Node using the following statement:

    Set tv.Nodes.Item(strKey).Parent = tv.Nodes.Item(strPKey)

    Here,

    • strKey = current record’s Node Key (ID),

    • strPKey = ParentID value.

    This is achieved by resetting the record pointer with:

    rst.MoveFirst

    and then looping through all records again with the usual pattern:

    Do While Not rst.EOF '… Node reassignment logic … rst.MoveNext Loop

    The key benefit of this two-pass approach is that it guarantees parent Nodes exist before child reassignment. This avoids the “Element Not Found” error entirely and ensures the TreeView hierarchy always reflects the current state of the data—even after drag-and-drop operations have reshaped the relationships.

    Second Step in Reverse Order.

    Alternatively, you can approach the second pass in reverse order.

    After all records have been populated as Root-level Nodes, the record pointer will naturally be positioned at the end of the recordset (EOF). From there:

    1. Reset the pointer to the last record using:

      rst.MoveLast
    2. Begin a loop with a BOF check, and for each iteration, move the pointer backwards with:

      rst.MovePrevious
    3. Within the loop, reassign each Node under its Parent Node as required.

    This method ensures that every Node is being created in the TreeView when its children are processed—just like in the forward pass. However, you may notice that the visual placement order of Nodes in the TreeView differs slightly compared to the forward-loading method.

    I encourage you to try this reverse-order approach yourself with the code changes above and observe the results.

    Download Demo Database.


    1. MS-Access Class Module and VBA
    2. MS-Access VBA Class Object 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 Transformation

        Share:
        Listen to this article
        Ready to read.

        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 External Links Queries Array Class Module msaccess reports Accesstips msaccess tips WithEvents Downloads Objects Menus and Toolbars MsaccessLinks Process Controls Art Work Collection Object Property msaccess How Tos Combo Boxes ListView Control Query VBA msaccessQuery Calculation Dictionary Object 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 Recordset Top Values Variables msaccess email progressmeter Access2007 Copy Excel Expression Fields Join Methods Microsoft Numbering System RaiseEvent Records Security Split SubForm Table Tables Time Difference Utility WScript Workgroup Wrapper Classes 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 Export 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