質問

I am going to do my best to explain this, though admittedly I have not attempted much in months so I'm not only rusty, I wasn't good to being with.

I am using visual web developers and asp, vb is the code behind with a sql db.

If I select a columns from a table, for example:

sqlCmd.CommandText = "SELECT Username, W1, W2, W3, W4 FROM tablename"

Say there are multiple rows in this table with data in these columns.

When I do a datareader, or how I have been shown, I declare dr like:

Dim dr As Data.SqlClient.SqlDataReader

I can work with the selected items such as:

dr.item(0)
dr.item(1)

etc.

But the only items I can work with are the first row of items selected. How do I select all of the rows in the table. Or how can I work with the data from multiple rows using dr.item or by somehow telling it to move onto the next row so that dr.item(0) becomes the username for the second row in the table.

I hope that made sense and I'm sorry if this is a stupid question. I appreciate the time and help in advance. Thanks guys.

役に立ちましたか?

解決

SqlDataReader.Read advances the reader to the next record and returns true when there is at least one other row:

Using conn = New SqlClient.SqlConnection(connString)
    Using cmd = New SqlClient.SqlCommand("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
        conn.Open()
        Using dr = cmd.ExecuteReader()
            While dr.Read()
                Dim UserName As String = dr.GetString(0)
                ' ... '
            End While
        End Using
    End Using        
End Using

Use Using to dispose anything that implements IDisposable as soon as possible. It will also close connections implicitely.

Edit: using a DataTable

How do I select all of the rows in the table

The DataReader approach above works well, but if you want to select all rows anyway and it's ok to load all into memory, you can use a DataTable instead. Then you could also access each row via indexer like an array or list:

Dim tblUsers = New DataTable()
Using conn = New SqlClient.SqlConnection(connString)
    Using da = New SqlClient.SqlDataAdapter("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
        da.Fill(tblUsers)
    End Using
End Using
' access a row via index: '
Dim row10 As DataRow = tblUsers.Rows(9)
Dim user10 = row10.Field(Of String)("Username")
' of course you can also iterate all rows: '
For Each row As DataRow In tblUsers.Rows
    Dim userName = row.Field(Of String)("Username")
Next

他のヒント

To iterate through the rows of Data Table you need to use the following method:

while dr.read()
 Dim col1=dr.item(0)
 Dim col2=dr.item(1)
End while

So that You can each Attribute of ALL Rows.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top