4.6. Adding Records with a GUID Primary Key
Problem
You want to add records to
a
DataTable that uses a GUID as its primary key and
has related child records.
Solution
Use the DataTable.RowChanging
event handler.
The sample code contains three event handlers:
Form.LoadSets up the sample by creating a
DataSetcontaining two tables, a parent and child, both having a GUID primary key column with theDefaultValueset to a new GUID. A relation based on the parent table GUID and a foreign key GUID in the child table is added to theDataSet. The default view of the parent table is bound to the data grid on the form. Event handlers are added for theRowChangingevent in both the parent and childDataTableobjects.- Parent
DataTable.RowChanging Sets the default value of the primary key column in the parent table to a new GUID value when a new row has been added to the parent table.
- Child
DataTable.RowChanging Sets the default value of the primary key column in the child table to a new GUID value when a new row has been added to the child table.
The C# code is shown in Example 4-9.
Example 4-9. File: AddGuidPKRecordForm.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 ...
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