Hi,

I have the following code in my form. I would like to retrieve data from the MS Access database to ListView1. What will be the code?

Public Class frmContacts
    Dim inc As Integer
    Dim MaxRows As Integer

    Dim con As New OleDb.OleDbConnection
    Dim ds As New DataSet
    Dim da As OleDb.OleDbDataAdapter
    Dim sql As String
    Private Sub frmContacts_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\AddressBook.mdb"
        con.Open()

        sql = "SELECT * FROM tblContacts"
        da = New OleDb.OleDbDataAdapter(sql, con)

        da.Fill(ds, "AddressBook")

        con.Close()

        MaxRows = ds.Tables("AddressBook").Rows.Count
        inc = -1
        Call ShowRecords_Click()
    End Sub
ListView1.View = View.Details
        Dim dt As DataTable = da.Table("AddressBook")

        For Each c As DataColumn In dt.Columns
            ListView1.Columns.Add(c.ColumnName)
        Next

        For Each r As DataRow In dt.Rows
            Dim item As New ListViewItem(r(0).ToString())

            For i As Integer = 1 To dt.Columns.Count - 1
                item.SubItems.Add(r(i))
            Next
            ListView1.Items.Add(item)
        Next
ListView1.View = View.Details
        Dim dt As DataTable = da.Table("AddressBook")

        For Each c As DataColumn In dt.Columns
            ListView1.Columns.Add(c.ColumnName)
        Next

        For Each r As DataRow In dt.Rows
            Dim item As New ListViewItem(r(0).ToString())

            For i As Integer = 1 To dt.Columns.Count - 1
                item.SubItems.Add(r(i))
            Next
            ListView1.Items.Add(item)
        Next

Thanks for the reply. I am getting the following error with the below code:

Error: 'Table' is not a member of 'System.Data.OleDb.OleDbDataAdapter'

The code is:

Private Sub LVWLaod()
        ListView1.View = View.Details
        Dim dt As DataTable = da.Table("AddressBook")

        For Each c As DataColumn In dt.Columns
            ListView1.Columns.Add(c.ColumnName)
        Next

        For Each r As DataRow In dt.Rows
            Dim item As New ListViewItem(r(0).ToString())

            For i As Integer = 1 To dt.Columns.Count - 1
                item.SubItems.Add(r(i))
            Next
            ListView1.Items.Add(item)
        Next
    End Sub

Please help.

Correction:

ListView1.View = View.Details
        Dim dt As DataTable = ds.Tables("AddressBook")

        For Each c As DataColumn In dt.Columns
            ListView1.Columns.Add(c.ColumnName)
        Next

        For Each r As DataRow In dt.Rows
            Dim item As New ListViewItem(r(0).ToString())

            For i As Integer = 1 To dt.Columns.Count - 1
                item.SubItems.Add(r(i))
            Next
            ListView1.Items.Add(item)
        Next
This article has been dead for over six months. Start a new discussion instead.