Reputation: 123
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 :
Thanks in Advance
Upvotes: 0
Views: 7234
Reputation: 123
Based on equisde's answer, I have come up with the following code that works for me:
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
Dim oleCommand As OleDbCommand
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cn = New OleDbConnection
If System.IO.File.Exists("C:\myfolder\fdfd.accdb") Then
cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myfolder\fdfd.accdb; Persist Security Info=False;"
End If
Try
Dim SQL As String = "SELECT * from [names]"
oleCommand = New OleDbCommand(SQL, cn)
da = New OleDbDataAdapter(oleCommand)
Dim table = New DataTable("[names]")
cn.Open()
da.Fill(table)
cn.Close()
Dim view As New DataView(table)
source1.DataSource = view
DataGridView1.DataSource = view
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Upvotes: 1
Reputation: 4512
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
Upvotes: 0