4.5. Adding Parent/Child Rows with Auto-Incrementing Keys
Problem
You want to insert related parent/child rows into a
DataSet where the primary key of the parent table
is an automatically incrementing value.
Solution
Use the DataColumn object’s
AutoIncrementSeed
and
AutoIncrementStep properties.
The sample code contains two event handlers:
Form.LoadSets up the example by creating a
DataSetcontaining a parent and child table. Each table has anAutoIncrementcolumn that is the primary key and has both a seed and step value of -1. A relation is created between the parent and child table. The default view of the parent table is bound to the data grid on the form.- Add Record
Button.Click Adds a new row to the parent table along with a random number of rows to the child table.
The C# code is shown in Example 4-8.
Example 4-8. File: AddParentChildAutoIncrementForm.cs
// Namespaces, variables, and constants using System; using System.Data; using System.Data.SqlClient; // Table name constants private const String PARENTTABLENAME = "ParentTable"; private const String CHILDTABLENAME = "ChildTable"; // Table column name constants for Parent table private const String PARENTID_FIELD = "ParentId"; private const String FIELD1_FIELD = "Field1"; private const String FIELD2_FIELD = "Field2"; // Table column parameter name constants for Parent table private const String CHILDID_FIELD = "ChildId"; private const String FIELD3_FIELD = "Field3"; private const String FIELD4_FIELD = "Field4"; private DataSet ...
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