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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to retrieve and display records from an Access database using DataReader object?

How-to

How to retrieve and display records from an Access database using DataReader object?

by  PankajBanga  Posted    (Edited  )

This sample refers to the System.Data.OleDb Class Library namespaces and NWIND.mdb (access database).

Imports System.Data.OleDb

Replace the Form_Load event handler with the following code.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'String variable to hold Connection String.
Dim conString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source = C:\Program Files\Microsoft Visual Studio\VB98\NWIND.mdb"
'Make sure you change the Data Source to the appropriate PATH.

'Create an oleDbConnection object,
'and then pass in the ConnectionString to the constructor.
Dim conn As OleDbConnection = New OleDbConnection(conString)

Dim selectString As String 'Variable to hold the SQL statement.
Dim cmd As OleDbCommand 'Create an OleDbCommand object.
Dim reader As OleDbDataReader 'Create an OleDbDataReader object.

Try
'Open the connection.
conn.Open()

'Initialize SQL string.
selectString = "SELECT EmployeeID, FirstName, LastName " & _
"FROM Employees "

'Initialize OleDbCommand object.
cmd = New OleDbCommand(selectString, conn)

'Send the CommandText to the connection, and then build an OleDbDataReader.
reader = cmd.ExecuteReader()

'Loop through the records and print the values.
While (reader.Read())
MessageBox.Show(reader(0).ToString & " " & reader(1).ToString & " " & reader(2).ToString)
End While

'Close the reader and the related connection.
reader.Close()
conn.Close()

Catch Excep As System.Exception
MessageBox.Show(Excep.Message, "Access Database", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top