Image of Navigational Panel mapped to Contents / Home / Search VB SQL Routine
Tech Support Question

Image of Line Break

Q. I have an Access 1.1 database which contain tables whose primary keys are counter fields. I would like to write a VB routine which saves a record to a table and returns the value of the counter field for the newly added record. Saving is no problem, but I cannot figure out how to return the new counter field value (i.e. primary key ).

Can anyone Help ?

Email: midnight@interlynx.net

A. This is actually very simple when you know how to do it. You will notice that in Access when you start to type data into a new row of a datasheet view that a number is allocated into the counter field of that record (for those tables that have counters, of course). The same thing actually happens in VB as well.

What is going on here is that a buffer is created for the entry of field values for the addnew. Because the Counter field is controlled by the database engine this is pre-populated by the dbengine when the buffer is created. That is why you see it in the datasheet view when you begin to create a new record. In VB you are doing the same thing. When you invoke the AddNew method of the RecordSet the same buffer is created and the counter is also preppopulated. Then that buffer is written to the table when you use the Update method. This means that before you do an Update the counter field is available for you to read.

The following code reads the new counter field number from the field called IDField before the record is written from the buffer into the table:

    Set ds = db.CreateDynaset("tablename")
    ds.Addnew
    ds!Name = "Fred"
    ds!Status = "Ridiculous"
    lNewID = ds!IDField
    ds.Update
    Msgbox "The new ID is: " & CStr(lNewID)

I hope that helps you do what you want to do, good luck.


Image of Arrow to Previous Article

[TECH SUPPORT TOC]
Image of Line Break
[HOME] [TABLE OF CONTENTS] [SEARCH]