Solved

Reading next row in a SQL table using DataReader

Posted on 2008-10-04
10
2,068 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
  • 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
 
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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…
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…

747 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now