tailieunhanh - Getting an AutoNumber Value from Microsoft Access

[ Team LiB ] Recipe 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. | Team LiB Recipe 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 Sets up the sample by creating a DataTable and programmatically defining the schema to match the Categories table in Northwind. The AutoIncrementSeed and AutoIncrementStep property values are both set to -1 for the AutoIncrement primary key column the CategoryID. A DataAdapter is created and used to fill the DataTable. The insert command and its parameters are defined for the DataAdapter so that new rows can be added to the data source. An event handler is defined for the RowUpdated event of the DataAdapter to retrieve the AutoNumber value generated for the CategoryID by Access. The default view of the table is bound to the data grid on the form. Add Creates a new row in the Categories DataTable using the entered CategoryName and Description values and the automatically generated CategoryID field. The Update method of the DataAdapter is used to insert the row into the data source and the DataAdapter RowUpdated event handler synchronizes the AutoNumber value generated by Access to the AutoIncrement column value its value both before and after is displayed. Retrieves the AutoNumber CategoryID value generated by Access for inserted rows and updates the DataRow with that value synchronizing it with the Access database. The C code is shown in Example 4-4. Example 4-4. File Namespaces variables and constants using System using using using using .