Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Assigning Images to Tree View Nodes

Introduction.

Last week, we have created the Access Project Menu to TreeView Control and I hope you were able to create it on your own and run it, in your version of Microsoft Access.  There is a Demo Database, created under Access 2007 and attached to the following article for download.  The Link to that Article is given below:

You may download the database so that you can add the new VBA Code, that pertains to the above topic, and try it out in the same Database.

This is the continuation of the earlier Article and we need the same Demo Access Menu Project to assign Images to Nodes.

MS-Office / Windows Version Issues for TreeView Control.

If you had any issues in running the Demo Database in your version of Microsoft Access then you may refer to the following link for some corrective actions, which may be helpful to solve your issue:

Sample Demo Image.

When we complete our Access Project MenuImages on Nodes will look like the Image given below:

Optionally, we can assign two Images on each Node.  One Image is displayed in a normal state and a different one is displayed when the Node receives a Click. 

Here, we have assigned the Root-level Node with the Closed-Folder Image for normal view and the Open-Folder-like Image will appear when the Node receives Click.

Similarly, the Child-Nodes have an Arrowhead Image, facing to the left side, in normal view, and another Arrowhead Image pointing to the right is displayed, when the Node is selected.

You can use the same Image for both (normal and for Click Event) so that the same image stays without any change in both instances.  If you use either one of these two parameters, say use the Normal View parameter only and omit the second one, then the Node click will not display any image.

Ideal Image Sizes for Nodes.

The Image format can be of any common image type, like bmp, jpg, jpeg, ico, tiff etc.  You can find plenty of Icon images by searching on Google.  The Ideal Image size, which looks good on the Node, is 16 x 16 pixels.  The ImageList Control has preset Image-size values like 16 x 16, 32 x 32, 48 x 48  pixels, and Custom Size Options to choose from.

Higher Image Size Options 32 x 32 or 48 x 48 Pixels will display larger images and occupies more space on the Tree View Display.

Node Graphics with Different Image Sizes.

The following sample image below shows a 32 x 32 Pixels size Icon:

TreeView Control with Node Image Size 48 x 48 Pixels:

If you prefer to use Custom Image Option then the actual image size provided will be displayed without change.

Image Quality and Size Considerations.

We have used Image Size 16 x 16 in the first sample Image above.  If we upload a Custom Image size, larger than 48 x 48, like  512 x 512 Pixels or more, and use the Option 16 x 16 it reduces the size to the resolution specified but the clarity of the image will be reduced or distorted.

The best approach is to find small images with better quality, that can fit into the 16 x 16 pixels resolution (canvas size).  It works with both 16 x 16 pixels or custom settings, without degrading the quality of the image.

You may experiment with different image types, sizes, and quality, and do trial runs before finalizing.  You may use MS-Paint, or whatever Image editing programs you have and create/Import and edit images to your liking.

Before proceeding further create four or more small images and save them in the database folder itself.  Upload them into the ImageList control and try them on the Tree View Control, by changing the Nodes Add() method’s last two parameters. 

You may Download the Demo Database: ProjectMenu.accdb, from the earlier Article Page.

Prepare for the Trial Run.

  1. Open the ProjectMenu.accdb database.

  2. Make a copy of the Form frmMenu and name it as frmMenu2 and keep it for later use.

  3. Open frmMenu in Design View.

  4. Select ActiveX Controls Option, from the Controls Button Group, find the file Microsoft ImageList Control and click OK to insert an ImageList control, drag and place it anywhere in the empty area on the Form.

    Form with ImageList Control highlighted in Design View is given below for reference:

  5. Display its Property Sheet and change the Name Property value to ImageList0.

  6. Right-Click on the ImageList Control and highlight the ImageListCtrl Object Option in the displayed Menu and Select Properties to display the Control’s Image settings Property Sheet.

  7. Select the 16 x 16 image size Radio Button on the General Tab, indicating that we need the smallest of the three image sizes for the Node.  The setting here takes effect on all Images we add to the ImageList Control.

  8. Click Apply Command Button and then the OK button to close the Property Sheet.

First, we must add the required images to the ImageList Control before we can use them in Tree View Control.

Image Loading Approaches.

There is an easy way and a hard way to Add Images to the ImageList Control.  The easy way works without VBA Code and the other method needs VBA.  We will go by the hard way first with VBA and then try the easy way, so you will know the difference between when to use code and when without Code.  A VBA-based method is good for experimenting, with different image sizes before finalizing what looks good on the Node.

We will use the ImageList Object’s Add() method to add images to the Control like we did for Tree View data for Node.  This way we add several images to the ImageList control and use them at run-time.

The Syntax of Add() Method of ImageList control is as given below:

ObjImgList.ListImages.Add([Index],[Key],[Picture]) As ListImage

The first two parameters are optional. The third argument uses the LoadPicture() Function to open images from the specified location and add it to the list. The function parameter is the Image File Path Name.  All the image files are added, one after the other to the ImageList Object, in the Order they are placed.  The Index values are automatically generated, in consecutive numbers starting from 1 (one) onwards.

After adding all the images to the ImageList Object, the Object reference must be passed over to the Tree View Control’s ImageList Property

The VBA Code.

The sample VBA Code for loading images for our Menu above is given below:

Dim tvw As MSComctlLib.TreeView
Const KeyPrfx As String = "X"
Dim objimgList As MSComctlLib.ImageList

Private Sub CreateImageList()
Dim strPath As String

'TreeView Object reference set in tvw
Set tvw = Me.TreeView0.Object
'Clear the Tree View Nodes, if any.
tvw.Nodes.Clear

'ImageList Object reference set in objimglist
Set objimgList = Me.ImageList0.Object

strPath = CurrentProject.Path & "\"

With objimgList.ListImages
'Key Names are Case sensitive.
    .Add , "FolderClose", LoadPicture(strPath & "folderclose2.jpg")
    .Add , "FolderOpen", LoadPicture(strPath & "folderopen2.jpg")
    .Add , "ArrowHead", LoadPicture(strPath & "arrowhead.bmp")
    .Add , "LeftArrow", LoadPicture(strPath & "LeftArrow.bmp")
    .Add , "RightArrow", LoadPicture(strPath & "RightArrow2.bmp")
End With

With tvw
    .ImageList = objimgList
End With

End Sub

Once we are through with this procedure it is easy to add the images to the Tree View Nodes.

The TreeView Nodes' Add() Method and Image Parameters.

The Tree View Object Add() Method’s last two parameters are for the Node Images.  Let us look at the TreeView Object Node's Add() method Syntax one more time:

tvw.Nodes.Add([Relative],[Relationship],[Key],[Text],[Image],[SelectedImage]) As Node

The last two parameters are for Node Images.  The first Image parameter is displayed for the Node’s normal view and the second image displays when the Node is selected.  The [Image] and [SelectedImage] values can be either the ImageList Index Number or the Key-Value.

The CreateImageList sub-routine adds five images to the ImageList Control.  Out of the first two Images, the first one (FolderClose) is for Root-level Node’s Normal View and the second one (FolderOpen) image is displayed when the root-level Node is selected.

The last two images are for the Child Node's normal view and for the Click Event action respectively.

The ArrowHead image is ignored. 

The Form_Load() Event Procedure Changes.

The modified FormLoad() Event Procedure is given below:

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

'1. Initializes TreeView Control Object
'2. Creates ImageList in ImageListObject
CreateImageList 

With tvw
    .Style = tvwTreelinesPlusMinusPictureText
    .LineStyle = tvwRootLines
    .LabelEdit = tvwManual
    .Font.Name = "Verdana"
    .Indentation = 400
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 = tvw.Nodes.Add(, , nodKey, strText, "FolderClose", "FolderOpen")
      
      '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 = tvw.Nodes.Add(PKey, tvwChild, nodKey, strText, "LeftArrow", "RightArrow")
     
     '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

The Add() method line of TreeView Nodes has been highlighted in the VBA Code above, where the Image Key String Parameter Values are inserted for both normal and Click Views of the Images.

Alternatively, you may use Image Index Values 1 and 2 for the Root-level Nodes, and Index Numbers 4 and 5 for the Child Nodes.

You may change the Values and try it out yourself.

A new Demo Database with all the changes and additional Image Loading procedures is attached for you to Download.

Note: Create four new images, as explained above, for your own trial runs and change the Image's Names and location Addresses in the above Code, if you save the images in a different location.

Next,  we will try out the easy method with the Images and I will share my Images with you.

Sample Database for Download.


  1. MS-Access and E-Mail
  2. Invoke Word- Mail Merge from Access2007
  3. Automated Email Alerts

Share:

3 comments:

  1. Hi APR, thanks for the post. I downloaded the sample but my code is erroring out on the LoadPicture lines, as the pictures were not included in the zip file. Any chance you could include the pics in the zip with the sample? Thanks!

    ReplyDelete
  2. The ImagesTreeView.zip File is added to the Page. Please download and Unzip the contents into the same TreeView Database Folder.

    ReplyDelete
  3. Mr Pillai, thank you so much. I was trying to add various pictures to my image control list from all over the internet, as well as Win 10, for open folder & closed folder. Yours worked! Much appreciated for this and your other instruction pages. The Common controls are very different from the list boxes and combo boxes I have been working with the last 25+ years, and your sample pages are very helpful. Best regards,

    ReplyDelete

Comments subject to moderation before publishing.

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