Free Programming Tutorials & Source Code

 
  • Increase font size
  • Default font size
  • Decrease font size
Home Visual Basic.NET Using DataReader in VB.NET

Using DataReader in VB.NET

E-mail
(1 vote, average: 4.00 out of 5)

In this tutorial we will work with DataReader to retrieve data from a MS Access database.
First of all, a DataReader is an ADO.NET object that provides read-only, forward-only data faster than a DataAdapter. It’s a good choice over the other objects for read-only purpose.
Also, it’s forward-only, means you cant go back to previous data which was accessed. The cursor in DataReader goes from top to button by using the Method Read.

To fill a DataReader with Data, we are going to use the OleDbCommand object and execute the result onto it.
First, we need to create a MS Access Database, with the following table in it:

Table Name: Position
Fileds:
ID, Number, Primary Key
Position, Text(50)


position table

And the code:


    Public Sub SelectAll()

        Dim cmd As New OleDb.OleDbCommand
        Dim strconn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Power\Desktop\db.mdb"
        Dim reader As OleDb.OleDbDataReader
        Dim conn As New OleDb.OleDbConnection(strconn)

        cmd.CommandText = "select * from Positions"
        ' Set the connection for the OleDbCommand
        cmd.Connection = conn
        'Open the connection
        conn.Open()
        'Execute the OleDbCommand
        reader = cmd.ExecuteReader()
        'Read data from DataReader
        While reader.Read
            ' Display data in a messagebox for testing purpose
            MsgBox(reader.Item("Position").ToString)
        End While

        ' Close the connection
        conn.Close()

    End Sub


Execute this code, what did you get? ;-)