While trying to read the value of a column, I am getting the error

Invalid attempt to read when no data is present

Code:

If reader.HasRows Then
  name = reader("UserFirstName").ToString
  MsgBox(name)
End If

reader.HasRows is returning True, but while printing 'name', the error happens.

PS: UserFirstName column name exists in the table.

1 Answers

2
Steve On

You need to call the Read method before trying to get something out of a DataReader even if you call HasRows and it returns true.
The call to Read is required because after executing the command to get back the reader this object doesn't contain the data from the first record and only after a Read you can start to get your data.

If reader.Read() Then
  name = reader("UserFirstName").ToString
  MsgBox(name)
End If

As you can see, you don't need the call to HasRows because if there are no records to read the Read method returns directly false.