I read What is the difference between "if (hasrows()) { while (read()) }" and "while (read()) { if (hasrows()) }"?, but the answer there doesn't really answer a similar question of mine.
What's the difference between
While reader.Read()
End While
and
If reader.HasRows Then
End If
and under which circumstances should either of them be applied? Am I wrong when I assume they both execute if there are any records found in the data reader?
The code in the While...End While
block will be executed for each row in Reader, while the code in the If...End If
block will be executed atmost only once, irrespective of how many rows the reader might have.
So when you want to repeat some action for each row in the reader you would use the While Reader.Read()
statement.
The If Reader.HasRows Then...
is typically used when your reader returns only one rows or no rows, and you want to perform some action based on that.
e.g.
If Reader.HasRows Then
MessageBox.Show("Record Found!")
Else
MessageBox.Show("The record was not Found!")
End If