A. Introduction.
Microsoft Tree View Control is part of Microsoft Windows Common Controls. It is an interesting piece of Object that displays related data in a hierarchy of Nodes. It can display related data, like entries and sub-entries in an Index List or listing of folders like Windows Explorer’s Left-Pane or a List of related Items in a hierarchical structure with Tree-Lines, Checkboxes, and Graphic Images.
The ListView and ImageList Controls are part of the Windows ActiveX Controls and we will be using them along with the TreeView Control in Microsoft Access.
I think you would like to look at some sample TreeView Control Demo Images, which we will be working on building in the coming few weeks.
B. Sample Demo Images.
Nodes in the Collapsed state.
- The Sample Demo TreeView Image with all Nodes in Collapsed form.
Nodes in the Expanded View.
- The above TreeView Control Nodes in the expanded view.
With Arrowhead Image Icons.
- The TreeView Sample Display, with arrowhead Image Icons displayed to the left of each Node Text.
Root-Level Nodes Have Folder Images others with Arrowhead.
- Next, the TreeView Display with linked data in a Sub-Form. Root level Nodes have two Images. The Folder-closed Image is displayed in normal mode. When the Root Level Node receives a Mouse Click it displays the Folder-open image and displays the Child-Nodes in expanded form.
Related information is displayed on the Sub-Form based on the selection of Root-level Node.
One of the Child-Node items selected displays another Form (normally kept hidden) with related information.
TreeView and ListView Controls.
- In the next picture of the Form, there are two Panels. The Product Category Item-related Nodes are in TreeView Control, in the left panel. When one of the Category items receives a Click on the TreeView control, related Product Items with Quantity and List Price in separate Columns will appear in ListView Control, in the right-side Panel.
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 shown at the beginning of this Page.
The above sample data table has three Fields.
The ID field is an AutoNumber field with Unique ID Numbers. The AutoNumber type is selected for our convenience. In either case, All records in the Table should have a Unique ID Value. If it is Numeric then it should be converted into String Type, before adding it to the TreeView Control.
The Second field is Node Description (Desc). The rows of information in this Column are logically related.
The third ParentID field is Numeric Type. But they should be converted to String Type before using it on TreeView Control.
We must know how the Description Column values are related to each other, based on that we can establish the relationship by entering related values into the ParentID field.
For example the logical arrangement of the relationship between the Author of Books, Publishers of the Books, the Book Stores where the Books are on Sale, or like Relationship between members of a Family Tree.
Relationship between Product Category, Products, Stock, Price, and so on. All this information may not appear under one Column in a single Table. They may appear in different Columns or on different tables as well.
The ParentID field is very important in that it determines the hierarchical arrangement of Nodes. If the ParentID Field is empty, then that record should go as a Root-level Node. The Child-Node always should have its ParentID filled in with its Parent records ID Value.
Root level Node can have one or more Child Node(s), and Child Node can have its own child Node(s).
We will load the above data into a TreeView Control and see how it looks. Then we will fill up the ParentId field with related IDs to change the view, the way we want to see it in a logical order.
D. Windows Common Controls Library file.
But, first thing first, open one of your Databases or create a new one.
Open the VBA Window (ALT+F11) and select References… from the Tools Menu.
Look for the File: Microsoft Windows Common Controls in the displayed list of files and put a checkmark to select it.
If you could not find the file in the list, click Browse... Button and find the file: MSCOMLIB.OCX in the Windows System directory, for Windows 7 Version look for the file in the SysWOW64 folder. Click OK to close the Library Files listing Control.
Save the Table with the name Sample.
Fill the Table with the sample data of 12 records as shown on the data view Image above.
E. Creating TreeView Control on Form
Create a New blank Form.
Click on the ActiveX Controls button from the Controls Group, find the Microsoft TreeView Control then select it.
Click OK to insert a TreeView control on the Form.
Drag the control down and to the right to leave some space at the top and left of the TreeView Control. Drag the bottom right corner sizing handle towards the right and the bottom corner to make the control larger, like the sample image given below.
Display the Property Sheet of the control and change its Name Property Value to TreeView0, if it is different there.
Display the VBA Editing Window of the Form.
- 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
Save the Form with the name frmSample, but don’t close the VBA Window.
G. VBA Code Line-by-Line.
F. Access VBA Code.
Let us take a quick look at the VBA Code and understand what it does.
In the Global Declaration Area, of the Form Module, the Variable tv is the TreeView Object declaration. The KeyPrfx is declared as Constant, with String Type value “X”.
The TreeView Node’s Key-Value must be always of String Type and needs at least one non-numeric character present in the Node Key. Our sample Table Key Values are all in numeric form, we can convert and add them to the Constant value “X”. Numeric Value converted into String Type alone will not accept as Node-Key.
Note: If the Node-Key and Parent-Key values are already in Alpha or Alphanumeric form then the question of conversion doesn’t arise. All Node-Key values must be Unique.
In the Form_Load() Event Procedure, the Database and Recordset objects are declared. Four String Variables are also declared.
The statement Set tv = Me.TreeView0.Object statement assigns, the TreeView0 Object on the Form, to the object variable tv.
The OpenRecordset() statement opens the Sample Table Records using the SQL strSQL.
The Do While… statement ensures that the record set is not empty, if empty then exit the Loop and end the Program.
If there are records then the first record’s ParentId field is checked for the presence of some value there or not.
If it is empty then that record is TreeView control’s Root-level Node item. The Root level Node needs only the unique Node-Key Value, which we already have in the ID Field and Item Description Field value for Text Argument.
If the ParentID field has a value, then the record is a Child-Node (Child of Root-level Node, or a child of some upper-level Child Node) of the TreeView Object.
The next line creates the Key Argument Value in the nodKey String Variable, with the ID field Value, converted into a String and added to the constant prefix X, Node-Key becomes X1.
The rst!Desc field value added to the String Variable strText, simply for clarity and to make it short in the Nodes.Add() method’s Parameter listing, if the field reference is very long then this will keep the Add() method neat and tidy.
The next executable line: tv.Node.Add() calls the Add() method of the TreeView.Nodes Object to add the Node to TreeView0 Control on the Form frmSample.
The Syntax of the Add() method is given below for reference:
tv.Nodes.Add([Relative],[Relationship],[Key],[Text],[Image],[SelectedImage]) As Node
All six Parameters of the Add() method are optional. If you call this method without any parameters, then an Empty Root-level Node will be added and a blank tree-line will appear as an indicator in the TreeView control.
For TreeView Root Level Node requires the Key and Text Argument values.
For the Child Nodes, both [Relative] and [Relationship] Arguments are required. Omitting any one of them will insert the Node as a Root Node, but will not generate any error.
[Relative] is the NodKey of an existing Node, entered into the related record’s ParentID field. [Relationship] is a Constant tvwChild with numeric value 4, identifying it as a Child Node of Key-Value in ParentID Field.
The other Constant values for the Relationship Argument are used for positioning 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 may experiment by setting each Value in the Relationship Argument and running the Code in Debug Mode, after keeping the VBA Window and Form in Normal View side by side. Watch how the Nodes are getting arranged in each cycle of the code execution to understand.
These will be useful while editing the TreeView Control by Deleting an Item and inserting another item in its place or adding a new Node at a specific location.
A Node with [Relative] Key must exist in the Nodes Collection before attempting to add a child node, to that parent Node, otherwise the Add() method generates an error.
This process is repeated till all the records are processed in the record set.
Note: You may review the VBA Code again after the Demo Runs.
H. The First Trial Run.
Open the Form in Normal View. The Trial Run result will look like the Image given below.
It doesn’t look more than a normal Listbox. Remember, we have not filled in any value in the ParentID field in our Sample Table. We have to establish some relationship between the Items in the rows of Record to move and position them in a hierarchical order in the TreeView Control.
I. Understanding the Relationship between Records.
- Open the Sample Table and let us examine the Records and how they are related.
- Let us leave the Database item alone as a Root Item.
The Database Object also has some top-level objects: Application, DBEngine, Workspaces Collection, and Databases Collection, which we have omitted here.
- Then we have the Tables group Item with ID value 2.
- In the next Table, Fields, Field items are related to the Tables group. We want the Table, Fields, and Field items to line up under the parent Item Tables Group Record with ID value 2.
- Let us call the record Tables as the Parent Node, Table, Fields, and Field records as Child-Nodes.
J. Updating the ParentID Field.
- So we need to update the value 2 (Node-Key of Tables) in the parent ID field of Table, Fields, and Field records.
- Please update only those records and close the Table. When it is done the records will look like the Image given below:
-
Now, open your frmSample in Form View and check the TreeView Control. The result will look like the earlier one without any change. The changes already happened, but it is not visible to you.
K. The Property Sheet of TreeView Control.
- Turn the frmSample in Design View.
- Right-Click on the TreeView Control and highlight TreeCtrl_Object from the Shortcut Menu and select Properties.
The Property Sheet will look like the Image given below:
- Change the LineStyle Property Value = 1 (tvwRootLines) and Click the Apply button, then click OK to close the Property Sheet.
L. Run After the LineStyle Property Value Change
- Save the Form and open it in Normal View. Now, the Tree Lines appear correctly. The Tables Node has a plus (+) sign on the left side, indicating that this Node has one or more Child Nodes in the next level and they are not in expanded form.
- Click on the plus symbol to expand the Node and display the Child Nodes, with the same ParentID. When you click on the Minus Symbol the Child Nodes are collapsed and hidden, changing the symbol with a plus sign again.
- The display will look like the following Image when expanded:
M. The Parent ID Updating of Other Records.
We will update the Forms record ID Value (Node-Key Value) into Form, Controls, and Control records’ ParentID fields so that these records will list under the Forms Node as its Child Nodes.
Similarly, update the ParentID field of the Report, and Control records with Reports ID (Node-Key Value) Value so that Report and Controls items will position under the Parent Node Reports, as its Child Nodes.
Make changes to your Sample table records with the Parent ID values as shown below:
After the above changes, the TreeView Display will look like the following Image, when all the Nodes are in expanded form.
All Child Nodes related to the Root level Nodes: The Tables, Forms, and Reports are grouped as a list under their Parent Nodes. But a Child Node may have a parent Node, a grandparent Node, or a Great grandparent Node.
N. Arranging All Object in Logical Hierarchical Order.
For example, let us take the first Root-level Node Tables. Logically Field (with record ID 5) is directly related to the Fields collection (record ID 4), the Fields collection is related to Table and Table is part of Tables collection. Each item in the group (record number 5 to 2) is related one step up to the next level.
So let us position these Child Nodes correctly under their own Parent Node and see how it looks.
Open your Sample Table and change the ParentID values of the Tables related to Child Records as shown below:
- The Field with ID-5 record’s Parent is Fields, record with ID-4, hence we have updated the 5th record’s ParentID field with ID Number 4.
- Similarly, the 4th record’s ParentID field is updated with 3, and the 3rd Record’s ParentID is updated with record number 2.
Note: Don't assume that the items arranged in this way must be next to each other.
- After changes to the records save the Table and Open the frmSample to view the changes. Your Tree View display should look like the image given below, with all Nodes in expanded form.
The TreeView Control has its own Property Sheet and the settings influence its appearance. So we will make a change in one of its Properties, and come back to the Tree View again.
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).
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.
This is a terrific tutorial. Thanks much. The level of detail, the pictures, this helped me a lot.
ReplyDeleteThank you.
DeleteI tied to apply treeview exercise your posted here. Sir I am currently using Windows 10 and Microsoft access 10,... I tried to search the reference library - Microsoft windows common controls OR tried to browse MSCOMLIB or SysWOW64 …. I didn't get any of the above reference … is there equivalent reference library for windows 10 or is there any options
ReplyDeletethanks
I'm using a treeview in MS Access 365, and everything (so far) is great EXCEPT that Access isn't recognizing the SelectedNode property, so a user can't use the treeview to select a node and manipulate the interface based on that selection. Any idea what's wrong? Is there a setting I haven't switched on or off? Has the name of the collection since 2021?
ReplyDeleteYou can safely skip that part. The code still runs fine.
ReplyDeleteI have followed this word for word and get an error in the compile.
ReplyDeleteThe line in the Else section......
tv.Nodes.Add ParentKey, tvwChild, nodKey, strText
Yields a "Run-time Error '35601' Element not found.
Each attribute does have a value.
What am I missing.
MS Access 365, (version 2302), Windows 11
A Demo Database is attached now with two Demo Forms. Download and compare the Code with your VBA Code to track the Errors.
ReplyDelete