Solved

Reading next row in a SQL table using DataReader

Posted on 2008-10-04
10
2,083 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 59

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 59

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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
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 59

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 59

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 59

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

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!

Question has a verified solution.

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

If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
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.
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

733 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