Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

Assigning Images To ListView Items Tutorial-03

The ImageList ActiveX Control.

To assign images to the ListView control, we need the support of another ActiveX control: the ImageList control. You may have noticed how Windows Explorer displays icons—such as folders in a closed state, which change to an open folder when clicked, along with different icons for various file types. While the ListView control does not provide that level of flexibility, it does allow us to display icon images in Column Headers, List Items, and ListSubItems when populating their contents. The Sample Demo Images.

Sample Preview

The following image shows an example of the Northwind Trading Employees listing, where each employee’s details are displayed in the ListView control along with their small photo icons. These images are assigned through the ImageList control and linked to the ListView items, making the data both informative and visually appealing.

Note: Using larger image sizes will automatically increase the row height of the ListView records, so you can display bigger photos if required.

The following sample image shows the ListView control (displayed in the right-side panel) used together with the TreeView control. The TreeView ActiveX control was already introduced in an earlier tutorial series. For quick reference, you can find the list of TreeView Control Tutorial Series links at the bottom of this page.

In the above picture, icon images have been applied to all data columns as well as the column header labels to demonstrate how images can be displayed in the ListView control.

On the left panel, the TreeView control nodes show the familiar folder icons in open and closed states. These behave differently from the ListView items: when a TreeView node is clicked, the open-folder image is displayed; clicking the same node again reverts it to the closed-folder image.

The ListView Control Programming Tutorial Series.

I hope you have already gone through the ListView Control Tutorial Sessions 1 and 2 and are now ready to continue with this new episode on using the ImageList Control along with the ListView Control.

For your convenience, the links to the earlier tutorials are provided below. I encourage you to review them before proceeding, as they cover some of the basic concepts of the ListView Control along with supporting VBA code. This background will put you in a better position to follow along and clearly understand the new features we are adding in this session.

  1. ListView Control Tutorial-01.

  2. ListView Control Tutorial-02.

Source Data and Demo Form.

  1. Let’s begin by creating a new Form and preparing the Employees Table for our ListView Control demo project.

    1. Import the Employees Table from the NorthWind.accdb sample database.

    2. Create a new SELECT Query using the SQL statement provided below.

    3. Save this query with the name EmployeesQ.

    SELECT [TitleOfCourtesy] & " " & [FirstName] & " " & [LastName] AS [Employee Name], 
    Employees.EmployeeID, 
    Employees.Title, 
    Employees.HireDate, 
    Employees.Address, 
    Employees.City, 
    Employees.Region, 
    Employees.PostalCode, 
    Employees.Country, 
    Employees.HomePhone, 
    Employees.Extension, 
    Employees.Notes
    FROM Employees;
    
  2. If your Employees Table structure is different, don’t worry. For the first column value, I have combined three fields together to form [Employee Name]. For the remaining columns, you can use whatever fields you have—include all of them or just a few, and in any order you prefer.

    Steps to Set Up the Form

    1. Create a new Form and open it in Design View.

    2. From the ActiveX Controls List, insert a Microsoft ListView Control.

    3. From the same list, insert a Microsoft ImageList Control.

    4. Resize the ListView Control as shown in the sample image of the form (provided earlier).

    5. Move the ImageList Control to the top-right corner of the ListView control, as shown in the demo image. You can also place it anywhere convenient on the form.

    Note: The ImageList Control will not be visible when the form is opened in Normal View; it appears only in Design View for configuration.

  3. Select the ListView Control and open its Property Sheet.

    • Change the Name property to ListView1.

  4. Select the ImageList Control, open its Property Sheet, and

    • Change the Name property to ImageList0.

    Important: Both the ListView and ImageList controls come with their own dedicated Property Sheets. Some of their property names and values may also appear in the Access Property Sheet, but updates made there may not always reflect correctly in the controls themselves. For reliable results, always make changes in each control’s own Property Sheet.

    ListView Control Property Sheet.

  5. Right-click on the ListView Control, point to the ListViewCtrl Object option from the shortcut menu, and then select Properties.

    The General tab of the ListView Control Property Sheet will appear, as shown in the image below. 

  6. Change the property values on the General tab as shown in the image above.

    Next, we will begin by loading the Employees data into the ListView Control.

    The Form Module VBA Code

  7. Copy and Paste the following VBA Code into the Form's Class Module:

    Option Compare Database
    Option Explicit
    
    Dim lvwList As MSComctlLib.ListView
    Dim lvwItem As MSComctlLib.ListItem
    Dim ObjImgList As MSComctlLib.ImageList
    Dim db As DAO.Database
    Dim rst As DAO.Recordset
    
    
    Private Sub cmdClose_Click()
       DoCmd.Close acForm, Me.Name
    End Sub
    
    Private Sub Form_Load()
     Call LoadListView("EmployeesQ")
    End Sub
    
    Private Sub LoadListView(ByVal tblName As String)
        Dim strFldName As String
        Dim intCounter As Integer
        Dim j As Integer
        Dim strLabel As String
    
    'Assign ListView Control on Form to lvwList Object
    Set lvwList = Me.ListView1.Object
    'Set ObjImgList = Me.ImageList0.Object
        
    'Assign Form Header labels Caption Text
     strLabel = UCase(tblName) & " " & "IN LISTVIEW CONTROL - TUTORIAL-03"
     Me.Label8.caption = strLabel
     Me.Label9.caption = strLabel
     
     With lvwList
        '.Icons = ObjImgList
        '.SmallIcons = ObjImgList
        '.ColumnHeaderIcons = ObjImgList
        .Font = "Verdana"
        .Font.Size = 10
        .Font.Bold = True
     End With
     
     Set db = CurrentDb
     Set rst = db.OpenRecordset(tblName, dbOpenSnapshot)
     
     'Create Column Headers for ListView
     With lvwList
        .ColumnHeaders.Clear 'initialize header area
        For j = 0 To rst.Fields.Count - 1
            strFldName = rst.Fields(j).Name
       'Syntax:
       '.ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
            .ColumnHeaders.Add , , strFldName, iif(j=0,3200,2000)
        Next
     End With
     
     'Initialize ListView Control
      While lvwList.ListItems.Count > 0
            lvwList.ListItems.Remove (1)
      Wend
    
     With lvwList
     Do While Not rst.EOF And Not rst.BOF
    
       'Syntax  .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
            Set lvwItem = .ListItems.Add(, , CStr(Nz(rst.Fields(0).Value, "")))
            
       'Add next columns of data as sub-items of ListItem
            With lvwItem
       'Syntax     .Add Index,Key,Text,Report Icon,TooltipText
             For j = 1 To rst.Fields.Count - 1
                .ListSubItems.Add , , CStr(Nz(rst.Fields(j).Value, ""))
             Next
    
           End With
           rst.MoveNext
    Loop
    rst.Close
        'reset lvwItem object
        Set lvwItem = Nothing
    End With
    
    Set rst = Nothing
    Set db = Nothing
    End Sub
    
    

    Note:  The Red-Colored VBA lines of the ImageList control are commented out from executing for the time being, and we will enable them shortly.

  8. Save your Form with the Name frmEmployees.

  9. Open the Form in Normal View. 

    The EmployeesQ Query Records Listing will look like the following Image:

  10. Review of the VBA Code

    We have already reviewed most of the above VBA code in ListView Control Tutorial Sessions 01 and 02, with only a few additions specific to the ImageList Control. These include its declaration, initialization, and a few lines for setting the Font Name, Font Size, and Font Style.

    Another important change is in the LoadListView() procedure. In this version, the procedure accepts a Table or Query Name as a parameter. All query types—except Action Queries—as well as Access Tables and Linked Tables, are valid inputs. The specified Table or Query name is supplied when the program is called from the Form_Load() Event Procedure.

    All field names from the given Table or Query are used as Column Header Labels (the third parameter) in the ColumnHeaders.Add() method. The Index and Key parameters (first and second) are not used here, as the system automatically assigns Index values in sequence.

    • The fourth parameter specifies the column width in pixels. In our example, the first column is set to 3200 pixels to accommodate the Employee Name, while all other columns are set to 2000 pixels.

    • Alignment and Icon parameters for column headers are not used. By default, column headers are left-aligned. The available alignment options are:

      • 0 - lvwColumnLeft

      • 1 - lvwColumnRight

      • 2 - lvwColumnCenter

    You can view these options on the Column Headers Tab of the ListView Control Property Sheet:

    1. Click the Insert Column button and enter a temporary column name.

    2. Open the Alignment property to view the available options.

    3. Click Remove Column to delete the temporary column.

    Note: If you prefer to add Column Header Labels manually, instead of loading field names through VBA code, you can type them directly here. They will then appear as column headers when the data is displayed.

    A sample view of the Icon image on the left side of the header column names can be seen in the second demo image in the right-side panel at the top of this page.

    For the data itself:

    • The first column (Employee Name from the EmployeesQ query) is assigned to the ListItems.Text property using the .Add method. Here too, the Index and Key parameters are omitted—the system automatically inserts Index numbers as serial values.

    • From the second field onward, column values are added through the ListSubItems.Add() method of the ListView Control.

    Note: All values are stored as Text in ListItems.Text and ListSubItems.Text, regardless of their original data type in the source Table/Query. To prevent errors, the code checks for Null values and converts them to text using the CStr() function.

    The ImageList control.

    In the main program, the ImageList Control initialization statements have been temporarily commented out. These lines are highlighted in red in the code segment below. We will revisit, explain, and enable them once we are ready to proceed with uploading images into the ImageList Control.

    'Assign ListView Control on Form to lvwList Object
    Set lvwList = Me.ListView1.Object
    'Set ObjImgList = Me.ImageList0.Object
        
    'Assign Form Header labels Caption Text
     strLabel = UCase(tblName) & " " & "IN LISTVIEW CONTROL - TUTORIAL-03"
     Me.Label8.caption = strLabel
     Me.Label9.caption = strLabel
     
     With lvwList
        '.Icons = ObjImgList
        '.SmallIcons = ObjImgList
        '.ColumnHeaderIcons = ObjImgList
        .Font = "Verdana"
        .Font.Size = 10
        .Font.Bold = True
     End With
     

    The first red-highlighted statement initializes the ObjImgList object with the ImageList0 control placed on the frmEmployees form. Before making changes to the code, let’s first explore the available options for uploading images into the ImageList Control.

    About Uploading Images.

    The next step is to upload some sample images into the ImageList Control. This can be done in one of two ways.

    Before starting, prepare at least two small images in any popular format—such as JPG, JPEG, BMP, or PNG—with BMP being the preferred type. The ImageList Control supports the following standard image sizes (available on the General tab of its Property Sheet): 16×16, 32×32, 48×48 pixels, or a Custom size.

    To configure this:

    1. Right-click on the ImageList Control,

    2. Highlight ImageListCtrl Object,

    3. Select Properties,

    4. Then, on the General tab, choose your desired image size before uploading any images.

    If you have larger images and want to keep their original size, select the Custom option. Otherwise, choosing a predefined size will automatically scale the images, which may reduce their quality. Keep in mind that using very large images will increase the row height when displayed in the ListView Control.

    For best results, icon-style images are ideal. However, you should experiment with different sizes—large, small, and very small—along with the available options to determine what works best for your project.

    You can upload images into the ImageList Control in one of the following two ways:

    1. Upload Images from disk through VBA Procedure.

    The sample VBA Procedure will look like the Code Segment given below, taken from the  TreeView Control Tutorial:

      
      Set objImgList = Me.ImageList0.Object
      objImgList.ListImages.Clear
      
    strFolder = "D:\Access\TreeView\"
    With objImgList
        With .ListImages
             .Add Index:=1, Key:="FolderClose", Picture:=LoadPicture(strFolder & "folderclose2.bmp")
             .Add Index:=2, Key:="FolderOpen", Picture:=LoadPicture(strFolder & "folderopen2.bmp")
             .Add Index:=3, Key:="ArrowHead", Picture:=LoadPicture(strFolder & "arrowhead.bmp")
        End With
    End With
    
    With tvw 'TreeView Control
        .ImageList = objImgList 'assign imagelist Object to TreeView Imagelist Property
    End With

    The first statement initializes the objImgList object with the ImageList0 control on the form.

    The next statement clears any existing images in the ImageList control, ensuring it is ready for new uploads from disk. For this method to work consistently, the required image files must always be available on the disk.

    The method objImgList.ListImages.Add()  is then used to upload images from disk. When using named parameters, the parameter values can be provided in any order. For example:

    • Index := 1 can appear at the end of the line,

    • Key := "FolderClose" can be listed first,

    and so on.

    However, if parameter names are omitted, the parameters must be supplied in the following order:

             .Add 1, "FolderClose", LoadPicture(strFolder & "folderclose2.bmp")

    To display an image in the ListView control, you can reference it either by using the Image Index Number (e.g., 1) or by specifying the Key value (e.g., "FolderClose") as the Icon or SmallIcon parameter in the ListItems.Add() method.

    We used this same approach earlier in the TreeView Control Tutorial. You may refer to that page and download the demo database for reference.

    This method loads the images into the ImageList object instance in memory, without altering the physical ImageList control on the form. However, it is important to note that the source images on disk must always be available every time frmEmployees is opened.

    2. Uploading Images from disk manually.

    This is a one-time setup task: locating the images on disk and uploading them into the ImageList Control.

    The key advantage of this method is that once images are uploaded into the ImageList Control, they remain embedded in the control. You won’t need to reload them from disk each time the form is opened. Moreover, the ImageList control—with the images included—can be copied and reused in other projects, or even shared with colleagues, eliminating the need for duplicate image setup.

    For this demonstration, let’s use the manual upload method, which is the more reliable approach. Prepare two samples .bmp images with a resolution of 50 x 50 pixels (e.g., image1.bmp, image2.bmp) and keep them ready in a folder, such as D:\Access\, for reference.

    Now, follow these steps:

    1. Open frmEmployees in Design View.

    2. Right-click on the ImageList Control, highlight ImageListCtrl Object, and select Properties.

    3. On the General tab, select the Custom option to retain the original resolution of the uploaded images.

    At this point, the General tab of the ImageList Control will appear as shown in the image below.

    The Images tab View of the ImageList Control

    Note: After testing uploaded images in the ListView control, if you wish to try a different size option (48×48, 32×32, or 16×16), you must first remove all existing images. Then, return to the General tab, select the new size option, and upload the images again. The uploaded images will automatically be resized to match the selected option.

    In the sample below, two images have been uploaded using the Insert Picture command button. The first image is currently selected, shown in a slightly raised position. The Index control displays the value:1, while the Key textbox shows the text First. The Index value is generated automatically, but the Key value must be entered manually. Use a meaningful Key name that is easy to remember and logically relates to the data.

    Both the Index number and the Key text can be used in the Icon or SmallIcon parameters of the ListItems.Add() method.

    If you plan to rely on Index numbers, be sure the image upload sequence matches the data sequence in the ListView (for example, each employee’s name aligns correctly with their photo). However, a more practical approach is to use Key text values—such as an employee’s first name—since they are easier to associate directly with records. For generic icons, descriptive Key names (e.g., FolderClosed, FolderOpen) provide clarity about their purpose.

    Steps to upload images:

    1. Open the Images tab of the ImageList Control.

    2. Click Insert Picture, browse the file  'D:\Access\Image1.bmp' to select it, and click Open to upload the image.

    3. In the Key textbox, type a unique Key value (e.g., First).

    4. Repeat steps 2–3 for the second image (e.g., D:\Access\Image2.bmp), assigning it another unique Key value.

    Your ImageList Control is now configured with sample images and ready to display them in the ListView Control.

Assigning ImageList Object to ListView Object Properties.

To display images in the ListView Control, the following ListView Object properties must be linked to the ImageList Object:

  • ListView.ColumnHeaderIcons

  • ListView.Icons

  • ListView.SmallIcons

The next step is to assign the ImageList Object to the ListView Control through these properties in VBA code:

  • lvwList.ColumnHeaderIcons

  • lvwList.Icons

  • lvwList.SmallIcons

This must be done before you can use image references (Index or Key values) in the following methods:

  • ColumnHeaders.Add()

  • ListItems.Add()

  • ListSubItems.Add()

We have already added the necessary VBA statements in the LoadListView() procedure of the main program, but they are currently commented out. To activate them:

  1. Open the LoadListView() procedure.

  2. Locate the four lines of code (highlighted earlier in red).

  3. Remove the comment symbol (') at the beginning of each line to enable them.

  4. Update the code to include the appropriate Icon Index values in the method parameters.

For example, modify the following statements (originally shown in red in the main program) to use Icon Index numbers 1 and 2 for the Icon  SmallIcon parameters:

' Example modification in LoadListView() Set lvwList.ColumnHeaderIcons = objImgList Set lvwList.Icons = objImgList Set lvwList.SmallIcons = objImgList lvwList.ListItems.Add , , "Employee 1", , 1 ' Icon Index = 1 lvwList.ListItems.Add , , "Employee 2", , 2 ' SmallIcon Index = 2

This ensures that images stored in the ImageList Control are correctly displayed alongside the ListView items.

 With lvwList
 Do While Not rst.EOF And Not rst.BOF

   'Syntax  .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
       ' Set lvwItem = .ListItems.Add(, , CStr(Nz(rst.Fields(0).Value,"")))
       'Change to 
         Set lvwItem = .ListItems.Add(, , CStr(Nz(rst.Fields(0).Value,"")), 1, 2)
        
   'Add next columns of data as sub-items of ListItem
        With lvwItem
   'Syntax     .Add Index,Key,Text,Report Icon,TooltipText
         For j = 1 To rst.Fields.Count - 1
           ' .ListSubItems.Add , , CStr(Nz(rst.Fields(j).Value, ""))
           'Change to           
             .ListSubItems.Add , , CStr(Nz(rst.Fields(j).Value, "")),,"Click"
         Next

       End With
       rst.MoveNext
Loop
rst.Close

Since we have only two images available, we will use the first image (Index = 1) as the Icon parameter and the second image (Index = 2) as the SmallIcon parameter.

  • The Icon image is displayed only when the ListView display option is set to 0 - lvwIcon.

  • The SmallIcon image is displayed in all other ListView display options.

In the ListSubItems.Add() method, we have not assigned any image reference. Instead, we used the next parameter to specify a Tooltip text "Click". This text will appear as a tooltip when the mouse pointer hovers over any column from the second column onward.

After making these code changes:

  1. Save the form frmEmployees.

  2. Open the form in Normal View.

  3. You should now see the ListView display similar to the sample image shown at the top of this page.

The SmallIcon will remain visible in all ListView display modes, except for 'lvwIcon', which uses the larger Icon image.

Check the following sample ListView screenshots of Employee data for reference.

0 - lvwIcon View

ListView Icon View

2 - lvwList View

The first sample image at the top of this page shows the 03 - lvwReport view.
This is the only view that displays all column values in a datasheet-like format.

To explore other views:

  1. Open the form frmEmployees in Design View.

  2. Select the ListView control and open its Property Sheet.

  3. Locate the View property.

  4. Change the setting to try out each option (0 - lvwIcon, 1 - lvwSmallIcon, 2 - lvwList, 3 - lvwReport).

  5. Save the form and open it in Normal View to see how the data is displayed in each case.


👉 This hands-on test helps you understand how the same data looks in different ListView display modes and which one best fits your application.

Download the Demo Database.

 

  1. Microsoft TreeView Control Tutorial
  2. Creating an Access Menu with a TreeView Control
  3. Assigning Images to TreeView Nodes
  4. Assigning Images to TreeView Nodes-2
  5. TreeView Control Checkmark Add Delete
  6. TreeView ImageCombo Drop-down Access
  7. Re-arrange TreeView Nodes By Drag and Drop
  8. ListView Control with MS-Access TreeView
  9. ListView Control Drag Drop Events
  10. TreeView Control With Sub-Forms
Share:

3 comments:

  1. can I use imagelist and imagecombobox activex controls to show dropdown list with images

    ReplyDelete
  2. can I use imagelist with imagecombobox to show dropdown list with images

    ReplyDelete
  3. can I use imagelist and imagecombobox to show dropdown list with images

    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