BobSki
BobSki

Reputation: 1552

For Next loops continues every if at limit

I'm working on an application and for some reason I have an issue understanding something. I have code that looks like this....

dim number as integer



number = rs.recordcount (only 1 record - so number = 1)
for x = 1 to Number
'stuff
'stuff
    rs.moveNext
Next 

I'm assuming that once it gets to rs.movenext and then goes onto to Next, it should simply exit the loop - yet it seems to go back to the top of the loop even though there is no record. Anyone have any idea why that's happening?

Upvotes: 0

Views: 246

Answers (2)

Chris Dunaway
Chris Dunaway

Reputation: 11216

The main reason your loop does not terminate is that you have not given it any conditions that would cause it to terminate.

Also, VB does not check the loop limit each time through the loop. It only checks it at the beginning. The following code will still print 100 times even though the value of Number changed:

Dim Number As Integer = 100
For x As Integer = 0 To Number
    Console.WriteLine(x)
    Number = 99
Next

Upvotes: 1

Mathieu Guindon
Mathieu Guindon

Reputation: 71187

RecordCount returns the number of records that have been read, or something like that - it does not return the total number of records, that value isn't known until the recordset has been iterated.

So a For...Next loop can't iterate a recordset efficiently.

Try a While loop instead:

While Not rs.BOF And Not rs.EOF
    'stuff
    rs.MoveNext
Wend

Upvotes: 3

Related Questions