Setting Up Autoincremented Fields

When a new row is added to a DataTable, the empty row is created by calling DataTable.NewRow. The DataTable knows the schema for the row that it must create and instantiates the new row to match the schema. That means the new row holds the right DataColumns with the correct data types ready for you to set the data.

The DataColumn.AutoIncrement property can be set to tell the DataTable to set the value for a DataColumn automatically when a new row is created. This is an especially useful feature for DataColumns that represent the primary key of a table, since the key can be automatically created for you.

There are three important properties in the DataColumn that relate to autoincremented fields:

DataColumn.AutoIncrement Set to true to make this DataColumn autoincrement.

DataColumn.AutoIncrementSeed The starting value for autoincrementing.

DataColumn.AutoIncrementStep The step amount for each new value.

If the DataColumn is a computed column, then trying to set it as an autoincremented column will cause an ArgumentException. Computed columns are discussed in great detail in the section “Deriving DataColumn Values with Expressions and Computed Fields.”

If the data type of the DataColumn is not an Int16, Int32, or Int64, then it is coerced back into an Int32. This can cause a loss of precision if the DataColumn is a floating-point data type. If the DataColumn is a string DataType, setting it to autoincrement will coerce the type of the DataColumn back to integer.

Creating Autoincremented Field Code by Example

This code sample comes out of an updated PhoneBook sample application which is described in the section “Updating the PhoneBook Application with Constraints and Autoincremented Fields.” This code snippet sets the AutoIncrement property for the ContactID DataColumn in the table named l_newTable. The starting value is 10, and the step value is 5.

C#
l_newTable.Columns["ContactID"].AutoIncrement = true;
l_newTable.Columns["ContactID"].AutoIncrementSeed = 10;
l_newTable.Columns["ContactID"].AutoIncrementStep = 5;

VB
l_newTable.Columns("ContactID").AutoIncrement = True
l_newTable.Columns("ContactID").AutoIncrementSeed = 10
l_newTable.Columns("ContactID").AutoIncrementStep = 5

Updating the PhoneBook Application with Constraints and Autoincremented Fields

This sample application is based on the PhoneBook application presented in the earlier section “Designing a Phone Book Application with a DataSet.” It is located in the folder SampleApplicationsChapter6PhoneBook_Constraint_AutoIncrement_CSharp and PhoneBook_ Constraint_AutoIncrement_VB. This sample application demonstrates the use of UniqueConstraints, autoincremented fields, and checking DataColumns that may not have DBNull values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.134.154