4.3. Getting an AutoNumber Value from Microsoft Access
Problem
If you add a row into a Microsoft Access table that has an
AutoNumber column, the value assigned to the
column in the DataTable is replaced by a value
generated by the database. You need to retrieve the
new value to keep the
DataTable synchronized with the database.
Solution
Use the RowUpdated event handler to retrieve the new
AutoNumber value generated by Microsoft Access.
The sample code contains three event handlers:
Form.LoadSets up the sample by creating a
DataTableand programmatically defining the schema to match the Categories table in Northwind. TheAutoIncrementSeedandAutoIncrementStepproperty values are both set to -1 for theAutoIncrementprimary key column, theCategoryID. ADataAdapteris created and used to fill theDataTable. The insert command and its parameters are defined for theDataAdapterso that new rows can be added to the data source. An event handler is defined for theRowUpdatedevent of theDataAdapterto retrieve the AutoNumber value generated for theCategoryIDby Access. The default view of the table is bound to the data grid on the form.- Add
Button.Click Creates a new row in the Categories
DataTableusing the enteredCategoryNameandDescriptionvalues and the automatically generatedCategoryIDfield. TheUpdate( )method of theDataAdapteris used to insert the row into the data source and theDataAdapterRowUpdatedevent handler synchronizes theAutoNumbervalue generated by Access to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access