CHAPTER 22 ADO.NET PART II: THE DISCONNECTED LAYER
Enabling Autoincrementing Fields
One aspect of the DataColumn you can choose to configure is its ability to autoincrement. You use an
autoincrementing column to ensure that when a new row is added to a given table, the value of this
column is assigned automatically, based on the current step of the increase. This can be helpful when
you want to ensure that a column has no repeating values (e.g., a primary key).
You control this behavior using the AutoIncrement, AutoIncrementSeed, and AutoIncrementStep
properties. You use the seed value to mark the starting value of the column; you use the step value to
identify the number to add to the seed when incrementing. Consider the following update to the
construction of the carIDColumn DataColumn:
static void FillDataSet(DataSet ds)
{
DataColumn carIDColumn = new DataColumn("CarID", typeof(int));
carIDColumn.ReadOnly = true;
carIDColumn.Caption = "Car ID";
carIDColumn.AllowDBNull = false;
carIDColumn.Unique = true;
carIDColumn.AutoIncrement = true;
carIDColumn.AutoIncrementSeed = 0;
carIDColumn.AutoIncrementStep = 1;
...
}
Here, you configure the carIDColumn object to ensure that, as rows are added to the respective table,
the value for this column is incremented by 1. You set the seed at 0, so this column would be numbered
0, 1, 2, 3, and so forth.
Adding DataColumn Objects to a DataTable
The DataColumn type does not typically exist as a stand-alone entity; however, you do typically insert it
into a related DataTable. For example, create a new DataTable object (fully detailed in a moment) and
insert each DataColumn object in the columns collection using the Columns property, like so:
static void FillDataSet(DataSet ds):
{
...
// Now add DataColumns to a DataTable.
DataTable inventoryTable = new DataTable("Inventory");
inventoryTable.Columns.AddRange(new DataColumn[]
{ carIDColumn, carMakeColumn, carColorColumn, carPetNameColumn });
}
At this point, the DataTable object contains four DataColumn objects that represent the schema of the
in-memory Inventory table. However, the table is currently devoid of data, and the table is currently
outside of the table collection maintained by the DataSet. You will deal with both of these shortcomings,
beginning by populating the table with data using DataRow objects.
866