Smith
Smith

Reputation: 5961

DAO.Recordset returns only one record when executing in codese

This statement always returns only one record everytime when its executed

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select book_name from book")
Dim i As Integer
For i = 0 To rs.RecordCount - 1
lbBooks.AddItem rs!book_name
rs.MoveNext
Next

what could ebe the cause

Upvotes: 2

Views: 6919

Answers (1)

Xophmeister
Xophmeister

Reputation: 9211

I believe that the RecordCount property of a Recordset is set dynamically to the amount of data that has been read from the cursor. That is, when it's first opened, it's set to 1; if you do rs.MoveLast, it will set it to the actual number of records in the set. However, you then have the problem of moving back to the start: you must have the recordset opened in a particular mode (which I forgot, from the top of my head) to be able to arbitrarily move the cursor pointer back and forward.

The usual way of iterating through a cursor is to use a while loop, checking for the cursor's end of file:

Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select book_name from book")
Dim i As Integer

i = 0 
While Not rs.EOF
  lbBooks.AddItem rs!book_name
  rs.MoveNext
  i = i + 1
Wend

Upvotes: 4

Related Questions