-2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    Possible duplicate of [Invalid attempt to read when no data is present](https://stackoverflow.com/questions/1147615/invalid-attempt-to-read-when-no-data-is-present) – Trevor May 03 '19 at 21:04
  • I don't agree with the duplicate vote. A) The duplicate refers to the same error but it is for a different language (OK minor) but B) The OP here is clearly misleaded by the HasRows call and thinks that it is enough to read the data. Needs to be explained and the duplicate has no mention of this. – Steve May 03 '19 at 21:22

1 Answers1

2

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.

Steve
  • 213,761
  • 22
  • 232
  • 286