Monday, March 19, 2012

DataReader not reading

Why won't this dataReader read?

Dim objCon2 As New SqlConnection()
objCon2.ConnectionString = "a standard connection string"
objCon2.Open()

Dim objCommand As SqlCommand
objCommand = New SqlCommand(strSQL, objCon2)
Dim objReader As SqlDataReader
objReader = objCommand.ExecuteReader()

Label1.Text = objReader("email")

strSQL is a select command which I've checked (using SQL Query analyzer) does return data. I know the connection string is valid (and I presume if it wasn't that it'd fail on objCon2.open, which it doesn't).

So why oh why do I get this error on the last line (and yes, there is an "email" field in the contents of the reader)

System.InvalidOperationException: Invalid attempt to read when no data is present.You have to move the "read head" to the start of a record by calling objReader.Read(). You do this each time you want to move to the next record. Since in your case there is presumably only one record you only need to call it once.


objReader = objCommand.ExecuteReader()
if objReader.Read()
Label1.Text = objReader("email")
End If
' be sure to close and the data reader afterwards
objReader.Close()