The following example uses the Biblio.mdb database as a source to populate a ListView control with ListItem objects. To try this example, place a ListView control on a form and paste the code into the Declarations section. You must also be sure that the Biblio.mdb has been installed on your machine. In the code below, check the path in the OpenDatabase function and change it to reflect the actual path to Biblio.mdb on your machine.
Note The example will not run unless you add a reference to the Microsoft DAO 3.5 Object Library. To do this, on the Project menu click References. Search for Microsoft DAO 3.5 Object Library and click the checkbox to select it.
Private Sub Form_Load()
' Add ColumnHeaders. The width of the columns is
' the width of the control divided by the number of
' ColumnHeader objects.
ListView1.ColumnHeaders. _
Add , , "Author", ListView1.Width / 3
ListView1.ColumnHeaders. _
Add , , "Author ID", ListView1.Width / 3, _
lvwColumnCenter
ListView1.ColumnHeaders. _
Add , , "Birthdate", ListView1.Width / 3
' Set View property to Report.
ListView1.View = lvwReport
' Declare object variables for the
' Data Access objects.
Dim myDb As Database, myRs As Recordset
' Set the Database to the BIBLIO.MDB database.
' IMPORTANT: the Biblio.mdb must be on your
' machine, and you must set the correct path to
' the file in the OpenDatabase function below.
Set myDb = DBEngine.Workspaces(0) _
.OpenDatabase("c:\Program Files\VB\BIBLIO.MDB")
' Set the recordset to the "Authors" table.
Set myRs = _
myDb.OpenRecordset("Authors", dbOpenDynaset)
' Declare a variable to add ListItem objects.
Dim itmX As ListItem
' While the record is not the last record,
' add a ListItem object. Use the author field for
' the ListItem object's text. Use the AuthorID
' field for the ListItem object's SubItem(1).
' Use the "Year of Birth" field for the ListItem
' object's SubItem(2).
While Not myRs.EOF
Set itmX = ListView1.ListItems. _
Add(, , CStr(myRs!Author)) ' Author.
' If the AuthorID field is not null, then set
' SubItem 1 to it.
If Not IsNull(myRs!Au_id) Then
itmX.SubItems(1) = CStr(myRs!Au_id)
End If
' If the birth field is not Null, set
' SubItem 2 to it.
If Not IsNull(myRs![Year Born]) Then
itmX.SubItems(2) = myRs![Year Born]
End If
myRs.MoveNext ' Move to next record.
Wend
End Sub