Question Display Access table in Datagridview

Tinkerbell

Member
Joined
Sep 9, 2009
Messages
14
Programming Experience
1-3
Hello, I have a table in Access called 'tblRealTime' with a few rows of data and I want to display it in a DataGridView object on my form. When I run the program I get no errors but nothing shows up in the datagrid. My code is below:

[
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\K0201227Project.accdb;Persist Security Info=False;"

SQLStr = "SELECT * FROM tblRealTime"


Dim OleDBConn As New OleDbConnection() 'The OleDB Connection
Dim OleDBCmd As New OleDbCommand() 'The OleDB Command
Dim OleDBdr As OleDbDataReader 'The Local Data Store

OleDBConn.ConnectionString = ConnString 'Set the Connection String
OleDBConn.Open() 'Open the connection

OleDBCmd.Connection = OleDBConn
OleDBCmd.CommandText = SQLStr 'Sets the SQL String
OleDBdr = OleDBCmd.ExecuteReader 'Gets Data


'create new dataset
Dim ds As New DataSet

Dim da As New OleDbDataAdapter(SQLStr, OleDBConn)
da.Fill(ds, "tblRealTime")

DataGridView1.DataSource = ds.DefaultViewManager


OleDBdr.Close() 'Close the SQLDataReader

OleDBConn.Close() 'Close the connection

]

Anybody know why it isn't working?

Thanks
Amy
 
You're opening a DataReader and then never using it, plus you're trying to use a DataAdapter over the same connection while it's open. DataReaders and DataAdapters are an either/or proposition. You use one or the other, depending on which is more appropriate under the circumstances.

There are various ways you could code it to work but the simplest would be:
VB.NET:
Using adapater As New OleDbDataAdapter(sqlQuery, connectionString)
    Dim table As New DataTable

    adapter.Fill(table)

    Me.DataGridView1.DataSource = table
End Using
No point creating, opening, closing and destroying a bunch of objects when most of it can be done for you.
 
Back
Top