Solved

Reading next row in a SQL table using DataReader

Posted on 2008-10-04
10
2,096 Views
Last Modified: 2012-05-05
Right now I have a table called Products with 4 columns, one of which is simply called ProductName. Using the attached code, I can read the first cell which contains "Clamp" and it successfully displays inside my text box. But how do I tell VB to simply read the next cell down?
I thought it would be as simple as using TextBox1.Text = thisReader(1) but it gives me the error "Index was outside the bounds of the array."

I'm still learning VB so give it to me simple :)
Dim thisCommand As New SqlCommand _
           ("SELECT ProductName FROM Products", _
            thisConnection)
 
        Try
            ' Open Connection
            thisConnection.Open()
            MsgBox("Connection Opened")
 
            ' Execute Query
            Dim thisReader As SqlDataReader = thisCommand.ExecuteReader()
 
            thisReader.Read()
            TextBox1.Text = thisReader(0)

Open in new window

0
Comment
Question by:Arka3L
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
10 Comments
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 22642546
use something like this:

If thisReader.HasRows Then    ' important, check if there are rows first, to avoid exception
     While thisReader.Read()
             '  do something with the row
     End While
End If
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22642555
The .Read() moves to the next record, so you can just do something like this:

While thisReader.Read()
    'Do something with value
    MsgBox(thisReader(0).ToString)
End While
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22642561
Jaime makes a good point.  The HasRows property is good to use before reading from SqlDataReader, but as you can see moving to next record is achieved by looping through thisReader.Read().

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader_members.aspx
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:Arka3L
ID: 22642568
I appreciate your guys' help and I've managed to have each cell loop and provide me the information, but maybe I didn't explain what I'm trying to do.

I don't want to use a loop for the program to start from the beginning cell and eventually loop through every value until I reach the last cell in that column. I want the value from what ever cell i want when i want it.

If i want the value from the 6th cell in the column, i want to call that cell, not loop through each one.

Thank you
0
 
LVL 1

Author Comment

by:Arka3L
ID: 22642575
My apologies from the confusion i've caused the readers and experts, i re-read the title of this question and understand it doesn't correctly portray the method i'm trying to accomplish.
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22642592
I would get your data back in a DataTable then and not a DataReader.  Then you can access whichever row/column combination you want.  If you want to maintain code that gets the data into DataReader, you can just use the DataReader to create DataSet or DataTable and then use that to display the exact data you want.
0
 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22642595
Here is an example: http://blogs.vbcity.com/drydo/archive/2007/10/17/8785.aspx.

The underlying concept is you use DataAdapter's to fill DataTables from DataReaders.

Hope that helps.

Regards,
Kevin
0
 
LVL 55

Expert Comment

by:Jaime Olivares
ID: 22642614
to read each cell, you can do something like:

Dim cell as String
thisReader.Read()
ForEach o As Object In this.Reader
     cell = o.ToString()
     ' do something with 'cell'
End If
0
 
LVL 1

Author Comment

by:Arka3L
ID: 22642615
I'm confused just reading that website you gave me, i'm so new to VB and what certain objects mean and do but i'm sure it contains the answer i'm looking for, I just don't know where to start lol. I'm going to post my entire code to show you what i have.

All I want the program to do (simply) without another 10 lines of useless code is to simply read the second cell of the ProductName column, or the third, or the fourth.

For example, if 0 inside the Reader is equal to the first cell, why cant i simply use 1 or 2 or 3. This is whats driving me up the wall, I don't understand why it can't be as simple as that.

Thank you for your patience.
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
 
        Dim thisConnection As New SqlConnection("Data Source=192.168.0.4,1433;Network Library=DBMSSOCN;Initial Catalog=TestData;User ID=******;Password=******;")
 
        Dim thisCommand As New SqlCommand _
           ("SELECT ProductName FROM Products", _
            thisConnection)
 
        Try
            ' Open Connection
            thisConnection.Open()
            MsgBox("Connection Opened")
 
            ' Execute Query
            Dim thisReader As SqlDataReader = thisCommand.ExecuteReader()
 
            If thisReader.HasRows Then    ' important, check if there are rows first, to avoid exception
                While thisReader.Read()
 
                    MsgBox(thisReader(0).ToString)
                    Last.Text = thisReader(0).ToString
 
                End While
            End If
 
 
            'Close DataReader
            thisReader.Close()
 
 
        Catch ex As SqlException
            ' Display error
            MsgBox("Error: " & ex.ToString())
        Finally
            ' Close Connection
            thisConnection.Close()
            MsgBox("Connection Closed")
 
        End Try
    End Sub
End Class

Open in new window

0
 
LVL 60

Accepted Solution

by:
Kevin Cross earned 500 total points
ID: 22642631
thisReader(0) means read the column at index 0 for the current row; therefore, you can use thisReader(1) or thisReader(6) to read different columns on the row you are on.  To be able to access random rows you need to use another class other than SqlDataReader which is why I suggested a DataTable.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Martin
Here are a few simple, working, games that you can use as-is or as the basis for your own games. Tic-Tac-Toe This is one of the simplest of all games.   The game allows for a choice of who goes first and keeps track of the number of wins for…
This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question