4.1. Using Auto-Incrementing Columns Without Causing Conflicts
Problem
You want to use an AutoIncrement
column in a table without producing values that may be duplicated in
records added by other users.
Solution
Use the AutoIncrementSeed and
AutoIncrementStep properties of the
AutoIncrement column.
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 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 entered CategoryName and Description values and the automatically generated CategoryID field.
The C# code is shown in Example 4-1.
Example 4-1. File: AutoIncrementWithoutConflictForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; // Table name constants private const String CATEGORIES_TABLE = "Categories"; // Field name constants private const String CATEGORYID_FIELD = "CategoryID"; private const String CATEGORYNAME_FIELD = "CategoryName"; private const String DESCRIPTION_FIELD = "Description"; private DataTable dt; // . . . private void AutoIncrementWithoutConflictForm_Load(object sender, System.EventArgs ...
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