Monday, March 26, 2012

Populate an array from a sql query?

I think I did something wrong with this. I am trying to create an array of product id's from a database query.


Dim dReader As SqlDataReader
Dim i As Integer = 0
Dim Products(i) As String
Dim strResults As String

conConnection.Open()
Dim cmdCommand As New SqlCommand("SELECT ProductID FROM Products WHERE CategoryID = '4'", conConnection)

dReader = cmdCommand.ExecuteReader()
While dReader.Read
Products(i) = dReader("Subcategory")
i += 1
strResults += dReader("Subcategory")
End While
Label1.Text = strResults 'just to display if I am getting results

conConnection.Close()

I put that StrResults so I can monitor if anything is getting picked up, but nothing happens at all. What did I do wrong?Doing this freehand so might be a little bit off.


Dim myArrayList as new ArrayList

Dim dReader As SqlDataReader

Dim i As Integer = 0

Dim strResults As String

conConnection.Open()

Dim cmdCommand As New SqlCommand("SELECT ProductID FROM Products WHERE CategoryID = '4'", conConnection)

dReader = cmdCommand.ExecuteReader()

While dReader.Read

myArrayList.Add(dReader("Subcategory"))

End While

conConnection.Close()

Dim x as Integer
For x = 0 to myArrayList.Count - 1
labeli.text += myArrayList(x) & " "
Next


Cool, thanks. I also noticed that I have Subcategory as my Datareader field, but CategoryID in my actual query.
 Dim cmdCommand As New SqlCommand("SELECT ProductID FROM Products WHERE CategoryID = '4'", conConnection)

dReader = cmdCommand.ExecuteReader()

While dReader.Read

Products(i) = dReader("Subcategory")

............

What did I do wrong?

-> You forgot to select "Subcategory" in SQL query?
Oh, sorry, didn't see you found it yourself.
Thanks guys. It feels so good when it finally works! :)

0 comments:

Post a Comment