Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL to load Access db records into data grid 1

Status
Not open for further replies.

faxpay

Programmer
Nov 30, 2004
119
US
Hi All,

I am a novice. I am using Visual Basic 2010 Express. Can someone help me with code for using an SQL stmnt to load records from an Access db into a data grid on a form?
I am somewhat familiar with SQL statements but need help with the vb2010 or .net code to load and display into data grid

Thank You
Tom
tnfaxpay
 

There are actually a few different ways to do what you want. I'll show you the one I use most often, which is creating all the objects in your code rather than using the wizards and whatnot.

First, at the very top of the form code, include this line:

Imports System.Data.OleDb

Next, add a DataGridView to your form and name it DataGridView1.

Add a button to your form, name it Button1 and double-click it to get to it's click event handler code. In there, put this:

Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim conn As OleDbConnection
    Dim ConnStr As String
    Dim da As OleDbDataAdapter
    Dim dt As DataTable
    Dim SQLStr As String

    ConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Path\To\Your\Database.accdb;"
  
    'Note: this connection string is for Access 2007 and later databases.  The connection string for earlier versions of Access is different.  Google "VB .Net connection strings" to get more info

    conn = New OleDbConnection(ConnStr)

    SQLStr = "Select * from <TableName>"  'use actual table name in place of <TableName>

    da = New OleDbDataAdapter(SQLStr, conn)

    dt = New DataTable

    da.Fill(dt) 'this is the line that actually queries the database

    DataGridView1.DataSource = dt

End Sub

That's pretty much it.

I used to rock and roll every night and party every day.  Then it was every other day.  Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys!  Ye needs ta be preparin' yerselves fer [url=www.talklikeapirate.com/piratehome.html]Talk Like a Pirate Day[/url]!
 
Thank You jebenson. That works great. Code was short and direct ans to my thread.

Tom
faxpay
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top