Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
TitleDisplay data from a database in a ListView control
KeywordsListView, database, ADO
CategoriesControls, Database
 
Use the ListView control's ColumnHeaders collection's Add method to add columns to the control. Use TextWidth to determine the columns' widths.

Use ADO to read the data. As you loop through the data, use the control's ListItems collection's Add method to make new rows. Place the the data from the ADO Recordset in the row's SubItems values.

 
Private Sub Form_Load()
Dim db_file As String
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim column_header As ColumnHeader
Dim list_item As ListItem

    ' Create the column headers.
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "Title", _
        TextWidth("Ready-to-Run Visual Basic Algorithms"))
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "URL", _
        TextWidth("http://www.vb-helper.com/vbgp.htm"))
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "ISBN", _
        TextWidth("0-000-00000-0"))
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "Pages", _
        TextWidth("Pages"))
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "CD", _
        TextWidth("False"))
    Set column_header = ListView1. _
        ColumnHeaders.Add(, , "Year", _
        TextWidth("0000"))

    ' Start with report view.
    mnuViewChoice_Click lvwReport

    ' Associate the ImageLists with the
    ' ListView's Icons and SmallIcons properties.
    ListView1.Icons = imgLarge
    ListView1.SmallIcons = imgSmall

    ' Get the data.
    db_file = App.Path
    If Right$(db_file, 1) <> "\" Then db_file = db_file & _
        "\"
    db_file = db_file & "books.mdb"

    ' Open a connection.
    Set conn = New ADODB.Connection
    conn.ConnectionString = _
        "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=" & db_file & ";" & _
        "Persist Security Info=False"
    conn.Open
    Set rs = conn.Execute("SELECT * FROM Books ORDER BY " & _
        "Title", , adCmdText)

    ' Load the data.
    Do While Not rs.EOF
        Set list_item = ListView1.ListItems.Add(, , _
            rs!Title)
        list_item.SubItems(1) = rs!URL
        list_item.SubItems(2) = rs!ISBN
        list_item.SubItems(3) = rs!Pages
        list_item.SubItems(4) = rs!CD
        list_item.SubItems(5) = rs!Year

        ' Get the next record.
        rs.MoveNext
    Loop

    ' Close the recordset and connection.
    rs.Close
    conn.Close
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated