Kristofer Gisslén
Kristofer Gisslén

Reputation: 1320

The difference between reading a datareader with a while-loop or an if-statement

This question doesn't really answer a question of mine I've been pondering about for a while even if it's close. 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 datareader?

Upvotes: 0

Views: 2057

Answers (3)

Pradeep Kumar
Pradeep Kumar

Reputation: 6979

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

Upvotes: 1

Psychemaster
Psychemaster

Reputation: 876

Simply put, yes, you are wrong in your assumption.

As you might expect, the While code block will execute once for every row in the returned result set - the Read() instruction returns false when no rows remain in the result set.

However, the If code block will execute exactly once, and only if there are rows in the result set.

In most cases, the While loop will be the one you want to use - even if there are no rows returned from the query, as the Read() call will return false and the entire code block will be skipped.

Upvotes: 0

Sathish
Sathish

Reputation: 4487

While reader.Read() End While

While loop Read the each line and executed.

If reader.HasRows Then End If

If reader has rows then only the block of codes work.

While loop used read all lines. but if condition used to only check if the reader has rows or not. if has row then do some work else do some other work.

Upvotes: 0

Related Questions