tailieunhanh - Adding Parent/Child Rows with Auto-Incrementing Keys

[ Team LiB ] Recipe 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. | Team LiB Recipe 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 Sets up the example by creating a DataSet containing a parent and child table. Each table has an AutoIncrement column 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 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 Namespaces variables and constants using System using using 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 Fieldl 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 ds . . . private void AddParentChildAutoIncrementForm_Load object sender e DataColumnCollection cols DataColumn col Build the parent table. DataTable parentTable new DataTable PARENTTABLENAME cols col PARENTID_FIELD typeof Int32 true -1 -1 FIELD1_FIELD typeof String .MaxLength 50 FIELD2_FIELD typeof String .MaxLength 50 Build the child table. DataTable childTable new DataTable CHILDTABLENAME cols .