Learn Microsoft Access Advanced Programming Techniques, Tips and Tricks.

ListView Control Tutorial-02

Introduction.

Continued from last week's ActiveX ListView Control Tutorial-01.

In this session of the Tutorial, we will learn how to search and find the particular row and column values and display them on a Label Control on Form. This is very useful when we have a large volume of data in the ListView control. We will also learn the usage of some ListView property settings.

First of all, we will see how easy is to rearrange the columns, like we do with Access Datasheet View the way we want them to be on the ListView Control. We have added some TextBoxes, ComboBox, Command Buttons, and Label for easier selection of search parameters and display of search results. 

I have made some changes to last week's demo data. The first column values I have taken from the Employees Table of Northwind.accdb sample database. Created a Query to join the LastName and FirstName Values with the field name Student and EmployeeID used as Key (X01, X02 ...).

ListView Tutorial-02 Screen View

Before going for the search operations, we will check how to re-arrange columns by the drag and drop method.

Note: If you have not gone through the earlier Tutorial Page and would like to continue with this session, then go to the ListView Control Tutorial-01 Page and download the demo database from the bottom of that Page.

Unzip the file and open the Database. The Demo Form will be in Normal View.

  1. Open your Database, with the last session's Demo Form, or the Form that you have created, open it in Normal View.

    Now, we will try to drag and move a column from the middle of the list (say the Weight column), and drop it to the Age column and see what happens. What is expected to happen is that the Age column should shift to the right and insert the incoming column in its place.

  2. Move the mouse pointer on the Column Header with the name Weight, click and hold the left mouse button. When you depress the left mouse button the column header will move slightly down.

  3. Now, try to drag the column to the left and drop it on the column Age.

    Nothing will happen, because we have not enabled this feature in the Property Sheet and that is the only setting, we need to change for this feature to work.

  4. Change the Form in Design View.

  5. Right-Click on the ListView Control and highlight the option ListViewCtrl Object and select Properties.

  6. There is an option 'AllowColumnReorder' on the right side. Put check-mark to select it, then click Apply button followed by the OK button to close the Property View.

  7. Now, try to repeat the above steps 2 and 3 above and see what happens. 

    That is the only setting you need to enable this feature on the ListView Control.  Perhaps you may be thinking, what about rearranging the rows?.

    That function needs programming some Event Procedures as we did earlier in TreeView Control Drag-Drop Events. That part we will do after some time.

  8. You may experiment with any column to move anywhere you like, including the first column as well.

Note: Before you drop the source column see that the target column is covered by the incoming column frame before attempting to drop.  Otherwise, the incoming column may shift to the next column position on the right side.

Next, we will learn how to find some information from the ListView quickly, assuming that we have a large volume of data in it.  

We have added a subroutine to Tutorial-01 Module to load the Column header Names into a Combo Box on the form with the red background color. The Column Name will be used to find the column value (Age, Height, Weight, or Class) of a student.

New VBA Code Added to the Form Class Module.

The following new VBA procedure is added to last week's Tutorial Form's Class Module: 

The txtColCombo creates the list of Column Header Labels (field names) in the ComboBox.  One of these details of the Student's Age, Height, Weight, or Class can be found along with the student's name as part of the search-and-find operation. 

Private Sub txtColCombo()
'Column Header List Combo
Dim lvwColHead As MSComctlLib.ColumnHeader
Dim cboName As ComboBox

Set cboName = Me.txtCol
cboName.RowSourceType = "Value List"

For Each lvwColHead In lvwList.ColumnHeaders
    If lvwColHead.Index = 1 Then
        'Nothing
    Else
        cboName.AddItem lvwColHead.Text
    End If
Next
'cboName.DefaultValue = "=txtCol.Column(0, 0)"

Set lvwColHead = Nothing
Set cboName = Nothing
End Sub

The Combobox will not be loaded with a default value of Column Header name. If selected that column value of the Student is displayed in the Large Label below the student Name. If it is left blank, the search operation will find the student's name only.

The search operation method is very flexible and quick.  We have two methods to find a record.

Find the record by providing the search text.  The search text can be from any of the columns either the text in full or partial few characters from the left. Since we have two categories of object members in a row in the ListView control: ListItem - the first column and other columns are ListSubItems.  The Text search operation on these objects is performed separately. 

An option group with two CheckBoxes is provided next to the search-text input TextBox on the Form to select the search-and-find options. The first option is selected by default and the search is performed on the first Column (ListItem) to look for the given text.

Select the second option to search the text in the ListSubItem columns.  

Note: Re-arranging the columns will not change the objects, but only their display position. Dragging a ListSubItem column and bringing it in the first column will not change it into a ListItem object.

If you want to retrieve an unknown value from a particular column, select a column name from the ComboBox given below the first TextBox on the Form for the search text. For example, you don't know the Height measurement of a student and would like to find out, select the column name Height from the ComboBox. 

After setting the above value(s) click on the Find Item Command Button to go for the search operation.  If the search was successful, then the result will be displayed in the large Label control below the Command Button.

The [Find Item] Command Button Click.

Calls the SearchAndFind() Procedure.

Private Sub SearchAndFind()
'Find by Student Name
Dim lstItem As MSComctlLib.ListItem
Dim strFind As String
Dim strColName As String
Dim strColVal As String
Dim j As Integer
Dim intOpt As Integer
Dim msgText As String

Me.Refresh
intOpt = Me.Opts


strFind = Nz(Me![txtFind], "")
strColName = Nz(Me![txtCol], "")

Select Case intOpt
    Case 1
        Set lstItem = lvwList.FindItem(strFind, , , lvwPartial)
    
        If Not lstItem Is Nothing Then
            j = lstItem.Index
            'format the display text
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & " : " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox "Text '" & strFind & "' Not Found!", vbOKOnly + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
    Case 2
        Set lstItem = lvwList.FindItem(strFind, lvwSubItem, , lvwPartial)
        If Not lstItem Is Nothing Then
       'format the display text
            j = lstItem.Index
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & ": " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox strFind & " Not Found!", vbOK + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
End Select

        If Len(strColName) = 0 Then 'If column name is not selected
            GoTo nextStep
        Else
            'Get the column value
            strColVal = GetColVal(lstItem, strColName)
            msgText = msgText & String(8 - (Len(strColName)), " ") & _
            strColName & ": " & Nz(strColVal, "")
        End If
nextStep:

If Len(msgText) > 0 Then 'assign to form label
    lvwList.ListItems.Item(j).Selected = True
    lblMsg.caption = msgText
End If

End Sub

At the beginning of the program, both the Student Name and Column Name (0ptional), are copied from the TextBoxes into the Variables strFind and strColName respectively after validation checks.

Note: The column name Combo Box's Not-in-List Property is set to Yes.  You can select a valid Value from the list or type it in or leave the combo box blank. If you type in a different value that is not in the list, it will not be accepted.

Based on the search Option selected (1 - ListItem or 2 - ListSubItem) the scan method is directed to the specified Object(s). 

Using either one of these search methods will find the ListItem Object or row that contains the search text. The Index Value of the ListItem is saved in Variable J for later use in the program. 

Note: The system creates the index auto-numbers automatically at the time ListView control items are populated. 

The ListItem.Text value is retrieved.   This information is joined with the first ColumnHeader. Text (like Student: Robert King) and added into the Msgtext string to display in the Label control on the Form.

If the column Header Name is selected in the ComboBox, then the GetColVal() Function is called with the ListItem Object and the Column Header Text value as parameters. This option is good for retrieving unknown information about a Student, like the Height of the student, from the record.

The GetColVal() Function VBA Code.

Private Function GetColVal(lvwItem As MSComctlLib.ListItem, ByVal colName As String) As String
Dim i As Integer
Dim strVal As String
    'first column is student name
    'check for column value from 2nd column onwards
    For i = 2 To lvwList.ColumnHeaders.Count
        If lvwList.ColumnHeaders(i).Text = colName Then 'if col name matches
            strVal = lvwItem.ListSubItems.Item(i - 1).Text 'get column value
            Exit For 'No further scanning required
        End If
    Next
GetColVal = strVal 'return the retrieved the value
End Function

The above function asks for two parameters. The first parameter is the ListItem, where the Student's name is found.  The second parameter is the Column Name. The selected student's Age, Height, Weight, Class values are stored in the ListItem.ListSubItems Objects.  The function looks through the lvwList.ColumnHeader values to find the matching column name, when found that column index number is used for retrieving column value from the ListSubItems Object and returns the value to the calling program.

The [Find By Key] Command Button Click Event Procedure.

We have another method added to find the Student's Name using the Unique Key-Value of ListItem if used while creating the ListItem List. Even though it is optional, it is better to add Unique Key String Value (should start with an alphabet character) rather than ignore it.

For example, if we have to find somebody's information by their identification number like Social Security Number, National Identity Card Number, Passport Number or Driving License Number and so on, one of this information can be used as the Key value to the ListItem. Finding a record with this Unique Value is very easy and swifter rather than the above search-by-text method.

The cmdKey_Click() Event Procedure.

Calls FindByKey() Subroutine.
Private Sub FindByKey()
Dim colHeader As MSComctlLib.ColumnHeader
Dim lvItem As MSComctlLib.ListItem
Dim lvKeyVal As String
Dim lvColName As String
Dim txt As String
Dim msgText As String
Dim varcolVal As Variant

lvKeyVal = UCase(Nz(Me!txtKey, ""))
lvColName = Nz(Me!txtCol, "")

If len(lvKeyVal) > 0 then
On Error Resume Next 
Set lvItem = lvwList.ListItems.Item(lvKeyVal) 'get the item by Key
If Err > 0 Then
    Err.Clear
    MsgBox "Key Value: '" & lvKeyVal & "' Not Found!", vbOKOnly + vbCritical, "cmdKey_Click()"
    On Error GoTo 0
    Exit Sub
End If
Else
	MsgBox "Please Provide a Valid Key-Value!",vbOKOnly + vbCritical, "cmdKey_Click()"
    Exit Sub
End If

txt = lvItem.Text 'get the student name
'format message text
msgText = lvwList.ColumnHeaders.Item(1).Text & " : "
msgText = msgText & txt & vbCr & vbCrLf

If Len(lvColName) > 0 Then 'if column name is given
    varcolVal = GetColVal(lvItem, lvColName) 'get column val of student
    msgText = msgText & String(8 - Len(lvColName), " ") & lvColName & ": " & varcolVal ' add it to display
End If

lvItem.Selected = True 'highlight the item on form
Me.lblMsg.caption = msgText 'assign details to form Label
End Sub

As you can see in the above subroutine we could directly find the ListItem where the Student's name is, with the use of the Key-value, with a single statement: Set lvItem = lvwList.ListItems.Item(xKeyVal).  

The Next line reads the ListItem Text (or name of the Student) into the Variable txt. The next two lines create the message text with the Student's Name in the msgText string variable.

The next If . . .Then statement checks whether a Column Name Value is entered in the combo box control. If it is found, then calls the GetColVal() Function with the required parameters to find the column value and retrieve it in varColVal Variable and returns to the calling program.  The Column Name and its value retrieved is added to the msgText string variable to display on the Label control on the Form.

The next statement highlights the record Row of the Student as a visual indication that the searched item is found in the row.  The msgText value is displayed in the Label's Caption Property on the Form.

The Full VBA Code on the Form Module.

Option Compare Database
Option Explicit

Dim lvwList As MSComctlLib.ListView 'ListView Control
Dim lvwItem As MSComctlLib.ListItem '
Dim ObjImgList As MSComctlLib.ImageList
Const prfx As String = "K"

Private Sub Form_Load()
    Call LoadListView
    Call txtColCombo
End Sub

Private Function LoadListView()
'Populate the ListView control with Student Details
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim intCounter As Integer
Dim strKey As String

'Assign ListView Control on Form to lvwList Object
 Set lvwList = Me.ListView1.Object
 
With lvwList
    .AllowColumnReorder = True
    .Enabled = True
    .Font = "Verdana"
    .Font.Bold = True
    .Font.Size = 9
    .ForeColor = vbBlack
    .BackColor = vbWhite
 End With
 
 'Create Column Headers for ListView
 With lvwList
    .ColumnHeaders.Clear 'initialize header area
    
   'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
    .ColumnHeaders.Add , , "Student", 2500
    .ColumnHeaders.Add , , "Age", 1200
    .ColumnHeaders.Add , , "Height", 1200
    .ColumnHeaders.Add , , "weight", 1200
    .ColumnHeaders.Add , , "Class", 1200
    
 End With
 
 'Initialize ListView Control
  While lvwList.ListItems.Count > 0
        lvwList.ListItems.Remove (1)
  Wend

'Student Names and Ids are taken from Employees Table
'through the StudentQ Query.
Set db = CurrentDb
Set rst = db.OpenRecordset("StudentQ", dbOpenDynaset)

With lvwList
    Do While Not rst.EOF And Not rst.BOF
        intCounter = rst![EmployeeID]
        strKey = "X" & Format(intCounter, "00") 'Key Value sample: X01
        
    'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
        Set lvwItem = .ListItems.Add(, strKey, rst![Student])
        
        With lvwItem
    'Syntax: .Add Index,Key,Text,Report Icon,TooltipText
            .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & Format(intCounter, "00"))

       End With
        rst.MoveNext
    Loop
rst.Close
Set rst = Nothing
Set db = Nothing
Set lvwItem = Nothing
End With
lvwList.Refresh

End Function


Private Sub cmdClose_Click()
   DoCmd.Close acForm, Me.Name
End Sub

Private Sub cmdFind_Click()
Call SearchAndFind

End Sub

Private Sub cmdKey_Click()
Call FindByKey
End Sub

Private Function GetColVal(lvwItem As MSComctlLib.ListItem, ByVal colName As String) As String
Dim i As Integer
Dim strVal As String
    'first column is student name
    'check for column value from 2nd column onwards
    For i = 2 To lvwList.ColumnHeaders.Count
        If lvwList.ColumnHeaders(i).Text = colName Then 'if col name matches
            strVal = lvwItem.ListSubItems.Item(i - 1).Text 'get column value
            Exit For 'No further scanning required
        End If
    Next
GetColVal = strVal 'return the retrieved the value
End Function



Private Sub txtColCombo()
'Column Header List Combo
Dim lvwColHead As MSComctlLib.ColumnHeader
Dim cboName As ComboBox

Set cboName = Me.txtCol
cboName.RowSourceType = "Value List"

For Each lvwColHead In lvwList.ColumnHeaders
    If lvwColHead.Index = 1 Then
        'Nothing
    Else
        cboName.AddItem lvwColHead.Text
    End If
Next
'cboName.DefaultValue = "=txtCol.Column(0, 0)"

Set lvwColHead = Nothing
Set cboName = Nothing
End Sub


Public Sub SearchAndFind()
'Find by Student Name
Dim lstItem As MSComctlLib.ListItem
Dim strFind As String
Dim strColName As String
Dim strColVal As String
Dim j As Integer
Dim intOpt As Integer
Dim msgText As String

Me.Refresh
intOpt = Me.Opts

strFind = Nz(Me![txtFind], "")
strColName = Nz(Me![txtCol], "")

Select Case intOpt
    Case 1
        Set lstItem = lvwList.FindItem(strFind, , , lvwPartial)
        If Not lstItem Is Nothing Then
            j = lstItem.Index
            'format the display text
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & " : " & lstItem.Text & vbCr & vbCrLf
        Else
           MsgBox "Text '" & strFind & "' Not Found in the List!", vbOKOnly + vbCritical, "cmdFind_Click()"
        Exit Sub
        End If
    Case 2
        Set lstItem = lvwList.FindItem(strFind, lvwSubItem, , lvwPartial)
        If Not lstItem Is Nothing Then
       'format the display text
            j = lstItem.Index
            msgText = lvwList.ColumnHeaders.Item(1).Text
            msgText = msgText & ": " & lstItem.Text & vbCr & vbCrLf
        Else
            MsgBox strFind & " Not Found!", vbOK + vbCritical, "cmdFind_Click()"
            Exit Sub
        End If
End Select

        If Len(strColName) = 0 Then 'If column name is not selected
            GoTo nextStep
        Else
            'Get the column value
            strColVal = GetColVal(lstItem, strColName)
            msgText = msgText & String(8 - (Len(strColName)), " ") & _
            strColName & ": " & Nz(strColVal, "")
        End If
nextStep:

If Len(msgText) > 0 Then 'assign to form label
    lblMsg.caption = msgText
    lvwList.ListItems.Item(j).Selected = True
End If
End Sub

Public Sub FindByKey()
Dim colHeader As MSComctlLib.ColumnHeader
Dim lvItem As MSComctlLib.ListItem
Dim lvKeyVal As String
Dim lvColName As String
Dim txt As String
Dim msgText As String
Dim varcolVal As Variant


lvKeyVal = UCase(Nz(Me!txtKey, ""))
lvColName = Nz(Me!txtCol, "")

On Error Resume Next
If Len(lvKeyVal) > 0 Then
Set lvItem = lvwList.ListItems.Item(lvKeyVal) 'get the item by Key
    If Err > 0 Then
        Err.Clear
        MsgBox "Key Value: '" & lvKeyVal & "' Not Found!", vbOKOnly + vbCritical, "cmdKey_Click()"
       On Error GoTo 0
        Exit Sub
    End If
Else
    MsgBox "Please Provide a Valid Key-Value!", vbOKOnly + vbCritical, "cmdKey_Click()"
    Exit Sub
End If

txt = lvItem.Text 'get the student name
'format message text
msgText = lvwList.ColumnHeaders.Item(1).Text & " : "
msgText = msgText & txt & vbCr & vbCrLf

If Len(lvColName) > 0 Then 'if column name is given
    varcolVal = GetColVal(lvItem, lvColName) 'get column val of student
    msgText = msgText & String(8 - Len(lvColName), " ") & lvColName & ": " & varcolVal ' add it to display
End If

lvItem.Selected = True 'highlight the item on form
Me.lblMsg.caption = msgText 'assign details to form Label
End Sub

Download the Demo Database from the following Link:



  1. Microsoft TreeView Control Tutorial
  2. Creating Access Menu with 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:

Tips and Tricks Android App In Google Play Store.

The LEARN MS-ACCESS TIPS AND TRICKS Articles at your Finger-Tip. Take all Articles with you in your Android Phone App, wherever you go, and learn them at your own pace.

 Install the Android App from Google Play Store Now.

Share:

Activex ListView Control Tutorial-01

Introduction.

In MS-Access we have ListBox control and mostly it will have only a few columns of data, to find the item(s) quickly. The source data for this control are either typed directly into the Row-Source Property as a Values-list or loaded from the source Table or Query. The Combo Box control keeps its data hidden and needs a click to reveal the list to select. These Objects are already built-in as Access Controls.

But, there is another List Control that we always use in our database, can you guess what it is? Yes, the Data Sheet View Control. The records are displayed from Table, Query. In all these cases we see data in Datasheet View as a big list.

But there are other groups of Controls too in Microsoft Access, the ActiveX Controls.  We are already familiar with one of these controls - the Common Dialog Control or File Browser control.  

Here, the topic is Windows ListView Control.  You can visualize it as an Object similar to Windows Explorer, where you can display Items with Image Icons, Small image Icons, as a List, or like the Explorer's Detail View Pane. You can load your Table / Query data into this control to display them in Datasheet View, re-arrange the Columns or Rows, Sort the rows, display Images next to items, and so on. Other Programming Languages, like VB6, VB.NET, C#, etc., use Windows ListView Control. We are going to see how we can use it in Microsoft Access Database.

A simple ListView Demo screen, with some quick sample data, is given below:

ListView Demo Screen

We will make the above image-like display the starting point of the ListView Control Tutorial. We have uploaded ten rows of data into the ListView control, with a few lines of the VBA Code.  The ListView ActiveX Control you may not find in the existing list of ActiveX Controls in Access.  We have to add this Control's Library file MSCOMCTL.OCX from C:\Windows\System32 folder into the Access Reference Library.  Once it is added you can find this control with the name Microsoft ListView Control, Version 6.0 among other ActiveX controls.

So, let us add the MSCOMCTL.OCX Library File to our database.  This is the source library of ActiveX Controls like ListView, TreeView, ImageList. If you have already gone through our earlier TreeView control tutorial Pages, then you are already introduced to this control. 

Windows Common Controls Library File.

Do the following to attach the MSCOMCTL.OCX File:

  1. Open your Database and open the VBA Editing Window (Alt+F11).

  2. Select References… from the Tools Menu.

  3. Click on Browse Button to find MSCOMCTL.OCX File (Microsoft Windows Common Controls.)

  4. Look for the above file in C:\Windows\System32\ Folder, if you have a 32 Bit System or you have Windows 11 Operating System.

  5. If you could not find it there, then look for the Folder C:\Windows\sysWOW64\ (64 Bit System), and there you will find this file.

  6. Select the file MSCOMCTL.OCX and Click Open Command Button to attach the file to your Database.

  7. Press Alt+F11 again to come back to the Database Window.

Let us design a sample Form to match the above Image given at the top of this page.

  1. Create a new Blank Form.

  2. Select the ActiveX Control Button from the Controls Group of options.

  3. Find and select the Microsoft ListView Control from the displayed list and click the OK button to insert a ListView control on the Form’s Detail Section.

  4. Click and hold on to the control’s resizing handle, at the right bottom corner, drag to the right and down to make it large enough like the sample image given above.

  5. Drag the ListView control itself to the right and down to give some margin to the left and leave enough space above to create a Heading Label.

  6. Click on the ListView Control to select it, if it is not in a selected state.

  7. Display the Property Sheet and change the ListView Control’s name to ListView1.

  8. Create a Label control above and change the Caption property value to ListView Control Tutorial. You may format the label Caption with font size, color, etc., the way you like it.

  9. Create a Command Button below the LlistView control and change its Name Property Value to cmdClose and its Caption Property Value to Close.  The completed design will look like the following when your design is complete:

    ListView  Design
  10. Now, Save the Form with the name: ListViewTutorial and keep the Form in design view.

  11. Press Alt+F11 to go back to the Form’s Class Module Window.

    The VBA Code.

  12. Copy and Paste the following Code into the Form's VBA Module, replacing existing lines of code if any:

    Option Compare Database
    Option Explicit
    
    Dim lvwList As MSComctlLib.ListView
    Dim lvwItem As MSComctlLib.ListItem
    Dim ObjImgList As MSComctlLib.ImageList
    Const prfx As String = "X"
    
    Private Sub cmdClose_Click()
       DoCmd.Close acForm, Me.Name
    End Sub
    
    Private Sub Form_Load()
        Call LoadListView
    End Sub
    
    Private Function LoadListView()
        Dim intCounter As Integer
        Dim strKey As String
    
    'Assign ListView Control on Form to lvwList Object
     Set lvwList = Me.ListView1.Object
     
     'Create Column Headers for ListView
     With lvwList
        .ColumnHeaders.Clear 'initialize header area
       'Parameter List:
    'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
        .ColumnHeaders.Add , , "Name", 2500
        .ColumnHeaders.Add , , "Age", 1200
        .ColumnHeaders.Add , , "Height", 1200
        .ColumnHeaders.Add , , "weight", 1200
        .ColumnHeaders.Add , , "Class", 1200
     End With
     
     'Initialize ListView Control
      While lvwList.ListItems.Count > 0
            lvwList.ListItems.Remove (1)
      Wend
        
     With lvwList
        For intCounter = 1 To 10
            strKey = prfx & CStr(intCounter) '
       'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
            Set lvwItem = .ListItems.Add(, strKey, "Student " & intCounter)
            'Add next columns of data as sub-items of ListItem
            With lvwItem
          'Parameters =      .Add Index,Key,Text,Report Icon,TooltipText
                .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
                .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & intCounter)
    
           End With
        Next
        'reset lvwItem object
        Set lvwItem = Nothing
    End With
    lvwList.Refresh
    
    End Function
  13. Save the Form with the name ListView Control Tutorial-01.

    Demo View of the Form.

  14. Open the Form in Normal View to have a look at our creation.

    If you find your form with the following image-like display then you are on the right track.

    We have to make some changes in the Listview control's Property settings. We have changed the ListView control's name as ListView1 in the Access's Property Sheet. But, ListView control has its own Property Sheet. We will use the ListView control's own property sheet to make changes to the control. Some of the Property Values are appearing on the Access Property Sheet also.

  15. Right-Click on the ListView control and highlight the ListViewCtrl Object option from the displayed options list and select Properties from the displayed shortcut menu.

  16. The Property sheet Image is given below:

    ListView Property View

    On the Property Sheet on the top, there are Tabs with groups of other options. We are on the General tab by default. On the General tab, there are options on the left side of the control and checkboxes on the right. We will make changes on only two Properties, the ListView control on the form is in a disabled state by default, we must enable it.

    The ListView control display can be changed to different modes like List items with big image Icons, with small Image Icons, in ListView, or in Report View - like it appears in the first Image above.

  17. Enable the ListView Control by putting a check-mark in the Enabled Property, on the right-side.

  18. Select the lvwReport option from the View drop-down list at the left side.

  19. Click on the Apply Button on the Control to save the change.

  20. Click the OK button to close the Property Sheet.

  21. Save the Form with the changes and then open it in normal View.

  22. You will find the same result looks like the Image given on top of this page, except for the form background color and other form properties.

The Program's Functional Diagram.

Before going to the VBA Code it will be interesting to know how the data items are loaded into the ListView Control. The data arrangement for a ListBox control is straightforward. But, the ListView control's data loading procedure is entirely different. It is not in the logical order that we normally perceive. Once you know the flow of data from the source to a single row in the form of a diagram, or let us call it a flow chart, it will not be difficult to understand the VBA Code and what it does.

The Data Flow Diagram.

VBA Functional Diagram
  1. The left top corner box represents the ListView control.

  2. As the first step of preparing the List is to create the list's heading labels or Column Headings.  You can see this in the diagram, column headings in red color.  This you can compare with the field headings in Table's Datasheet View.  Each Column Heading is loaded into the ListView control in the ColumnHeaders Object member.  The ListView control's ColumnHeaders.Add() method is called five times for assigning each column label, one after the other, into the ListView control.

  3. The action needed to execute the next five steps are important to note.  They represent a single record with five Data Fields. But they are loaded into the ListView control in two different sets of steps, or let us say that they are being loaded into two different Object members (ListItems and ListSubItems) of the ListView control.

    1. The first field (Column Value) is loaded into the ListView control's ListItems Object's Add method. If you look at the image on the top, the first record's first column value Student1 is loaded in the ListItems Object (ListView.ListItems.Add method)  of the ListView control.

    2. From the 2nd column onwards all other column values are loaded into the ListSubItems Object of the ListItems Object, one after the other. The ListSubItems.Add Method (ListView.ListItems.Item(x).ListSubItems.Add) is called four times to insert the Values into Age, Height, Weight, and Class columns individually.

  4. These two-level steps of actions are required to load a complete row of values into the ListView Control.  The diagram is drawn with two rows of data in the ListView control.

With the above picture in mind, I am sure you will not have any difficulty in understanding what the above VBA Code does in the Program.

Let us go to the VBA Code Segment-wise.

At the Global declaration area of the Module, we have declared the ListView Object, the ListItem Object, the ImageList Object and a Constant Variable with the String Value LV.

Dim lvwList As MSComctlLib.ListView
Dim lvwItem As MSComctlLib.ListItem
Dim ObjImgList As MSComctlLib.ImageList
Const prfx As String = "X"

The lvwList Variable is declared as a ListView Object, lvwItem is declared as a ListItem Object of ListView Control, ObjImgList is declared as an ImageList Object. ImageList Object is another ActiveX control that can be loaded with Image Icons for use in TreeView, ListView controls. We will keep the ImageList control aside for the time being and will take it up later. The Constant Prfx is used in ListItems.Add method's Key-Value prefix, one of the optional Parameters. The Key-value must be of String Type.

The LoadListView() Function is the main program.

Our ListView control's name on the Form is ListView1. The first statement in the program:

Set lvwList = Me.ListView1.Object 

Assigns the ListView1 control on the Form into the Object variable lvwList declared in the Global declarations area.

Next, we will get prepared to load the Column Header information.  First, we initialize the ColumnHeader object to ensure that it is empty.  When we repeatedly run the program the control has a tendency to retain the earlier loaded values in the control.  When you open and close this form more than once, after disabling the ColumnHeaders.Clear statement, you will know the difference. The same set of headings is added to the control every time and will appear in the control with empty rows below. 

This you can check and confirm manually.  Do the following:

  1. Open the Demo Form once then close the form,

  2. Open the Form in Design View.

  3. Right-click on the ListView Control, highlight the ListViewCtrl Object Option, and select Properties from the displayed list.

  4. Select the Tab with the Label Column Headers.

  5. There you can find the first Column Heading Name in a Text Control and above the Text control the Index Value 1.

  6. Point the Mouse Pointer to the right side of the Index number box, There a control will appear with arrows pointing to left, right directions.

  7. Click on the right-arrow to display other Column labels one by one in the Text control, with the change of index numbers.

  8. If you open and close the Form one more time the above Tab will have two sets of the same Column Heading Labels.

The ColumnHeaders.Add method syntax is as follows:
lvwList.ColumnHeaders.Add(Index, Key, Text, Width, Alignment, Icon)

All parameters are optional.

With lvwList
    .ColumnHeaders.Clear 'initialize header area
'Parameter List:
'Syntax: .ColumnHeaders.Add Index, Key, Text, Width, Alignment, Icon
    .ColumnHeaders.Add , , "Name", 2500
    .ColumnHeaders.Add , , "Age", 1200
    .ColumnHeaders.Add , , "Height", 1200
    .ColumnHeaders.Add , , "weight", 1200
    .ColumnHeaders.Add , , "Class", 1200
 End With 

The Index value is automatically assigned as 1, 2, 3 as running serial numbers. 

The Key value is of String data type, but not used for Column Headers, if needed it can be used.

Text Value is displayed on the control as Column Labels. 

Based on the data width size required to display below the column headings we can assign an approximate width value in Pixels. 

If the Text alignment value is omitted then the Left-alignment (0 - lvwAlignmentLeft) value is taken as default. It can be  Right Aligned (1 - lvwAlignmentRight) or Center Aligned (2 - lvwAlignmentCenter).

After loading the column heading labels the next step is to load the first-row first Column value of the first record.  Before that, we must initialize the ListItems Object with the following code segment:

'Initialize ListView Control
  While lvwList.ListItems.Count > 0
        lvwList.ListItems.Remove (1)
  Wend

The next Code block loads the record list items one row at a time and a total of ten rows of some constant values with few changes for demo purposes.  This process we have put within the For...Next loop runs ten times, creating ten rows of data.

With lvwList
    For intCounter = 1 To 10
        strKey = prfx & CStr(intCounter) '
  'Syntax: .ListItems.Add(Index, Key, Text, Icon, SmallIcon)
        Set lvwItem = .ListItems.Add(, strKey, "Student " & intCounter)
        
  'Add next columns of data as sub-items of ListItem
        With lvwItem
  ' Syntax: .ListSubItems.Add Index,Key,Text,Report Icon,TooltipText
            .ListSubItems.Add , strKey & CStr(intCounter), CStr(5 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 1), CStr(135 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 2), CStr(40 + intCounter)
            .ListSubItems.Add , strKey & CStr(intCounter + 3), ("Class:" & intCounter)

       End With
    Next
    'reset lvwItem object
    Set lvwItem = Nothing
End With

The first statement within the For...Next loop strKey = prfx & Cstr(intcounter) prepares the unique Key value for the first ListItem (first Column).  

All the parameters of ListItems.Add method is optional and the first three parameters Index, Key, Text is assigned in the same order as Column Headers and the other two parameters are an icon and a small icon image reference.

When the row value of the first column is assigned to the ListItem (lvwList.ListItems) this object reference is saved in the lvwItem object for easily calling the next level sub-object (ListSubItems object) to avoid writing a lengthy object reference:

lvwList.ListItems.Item(index).ListSubItems.Add() 

Expressed in the short form with lvwItem.ListSubItems.Add()

The ListSubItems.Add() method's first three Parameters and passing order is the same as ListItem after that comes the Icon image reference followed by the Tooltip Text parameter. 

To the Key value of each column, I have added the For...Next Loop's control variable's current running value + some value to make it unique on all columns.  The Key parameter value can be omitted, but it is a good idea to get used to it.

The ListSubItems.Add() method is called four times to add the second column onwards into the ListView control.

These steps are repeated nine more times to load all ten sample records into the ListView Control.

The above ListView Control Demo database is attached for instant running and learning.

In the next session of our tutorial, we will learn how to search and find value from the list view control and how to rearrange the Columns like we do in Datasheet View.

  1. Microsoft TreeView Control Tutorial
  2. Creating Access Menu with 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:

Translate

PageRank

MSA GURU : Access Tips & Tricks App

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

Want to Post Free Ads on the Web

Newsletter


Feed

Subscribe in a reader
Your email address:

Delivered by FeedBurner

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 Graph Charts Query VBA msaccessQuery Calculation Event List Boxes TreeView Control Command Buttons Controls Data Emails and Alerts Form ImageList Control Custom Functions Custom Wizards DOS Commands Data Type Key Object Reference ms-access functions msaccess functions msaccess graphs msaccess reporttricks Command Button ListView Control 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