RBK RBK - 1 month ago 12
Vb.net Question

Retrieving data from MSAccess Database from VB.NET

I want to retrieve data from the database. I am using MSAccess as a database. The problem I am facing here is that I am not able to fetch Data from MSAccess through vb.net.

Find Below code snippet that I am using.

Imports System.Data.OleDb
Public Class Form1
Dim cn As OleDb.OleDbConnection
Dim ds As DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim connectionString As String

connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\myfolder\fdfd.accdb;"

cn = New OleDbConnection

cn.ConnectionString = connectionString


ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * From names", cn)
da.Fill(ds, "names")


Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class


Error occurs at line:
da.Fill(ds, "names")


Here is error screenshot :

Error Screenshot

Thanks in Advance

Answer Source

Try to open your connection before filling the dataset

Imports System.Data.OleDb

Public Class Form1

Dim cn As OleDb.OleDbConnection
Dim ds As DataSet
Dim da As OleDbDataAdapter
Dim tables As DataTableCollection
Dim source1 As New BindingSource

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load

    cn = New OleDbConnection

    cn.ConnectionString =  "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myfolder\fdfd.accdb; Persist Security Info=False;"

    Try

        ds = New DataSet
        tables = ds.Tables
        cn.Open()
        da = New OleDbDataAdapter("SELECT * FROM [Names]", cn)
        da.Fill(ds, "names")
        cn.Close()
        Dim view As New DataView(tables(0))
        source1.DataSource = view
        DataGridView1.DataSource = view

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub
End Class