4.2. Getting an Identity Column Value from SQL Server
Problem
When you add a row into a
SQL Server table that has an identity 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
There are two ways to synchronize identity values generated by the data source: use either the first returned record or the output parameters of a stored procedure.
The sample uses a single stored procedure:
InsertCategoriesUsed to add a new Categories record to the Northwind database. The stored procedure returns the
CategoryIdvalue generated by the data source as both an output parameter and in the first returned record.
The sample code contains two 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 and theCategoryIDvalue generated by the data source can be retrieved using either the output parameter values or first returned record from theInsertCategoriesstored procedure. The default view of the table is bound to the data grid on the form.- Add ...
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