How to: Iterate through Records in a DataReader (Visual Basic) 

This example iterates through a data reader created using a data adapter's select command as well as maintaining a count of records read.

Example

Dim reader As SqlClient.SqlDataReader
Dim recordData As String = ""
Dim recordCount As Integer = 0
Dim i As Integer = 0

sqlConnection1.Open()

reader = sqlDataAdapter1.SelectCommand.ExecuteReader()

While reader.Read()

    For i = 0 To reader.FieldCount - 1
        recordData &= reader(i).ToString()
        recordData &= "-"
    Next

    recordData &= ControlChars.CrLf
    recordCount += 1
End While

sqlConnection1.Close()
MessageBox.Show("Records processed: " & recordCount)
MessageBox.Show("Data:" & ControlChars.CrLf & recordData)

This code example is also available as an IntelliSense code snippet. In the code snippet picker, it is located in Data - Designer features and ADO.NET. For more information, see How to: Insert Snippets Into Your Code (Visual Basic).

Compiling the Code

This example requires:

  • A project reference to System.data.dll.

  • Access to the members of the System.Data namespace. Add an Imports statement if you are not fully qualifying member names in your code. For more information, see Imports Statement.

  • A data connection named sqlConnection1.

  • A SQLDataAdapter object named sqlDataAdapter1.

Robust Programming

The following conditions may cause an exception:

See Also

Reference

OleDbDataReader Class
SqlDataReader Class
OdbcDataReader Class
OracleDataReader Class

Other Resources

Preparing Your Application to Receive Data
Editing Data in Your Application