Name

Constraints

Synopsis


ConstraintCollection cc = DataTable.Constraints;

Accesses the ConstraintCollection for the DataTable, providing access to the Constraint objects belonging to the DataTable. The Constraints property can be used to add, remove, and examine the UniqueConstraint and ForeignKeyConstraint objects in a DataTable.

Examples

There are two methods that can add a constraint to a table. The Add( ) method takes an argument specifying a reference to an existing constraint or takes arguments specifying whether a unique constraint or foreign key constraint is being added. The following example demonstrates adding a constraint by specifying a reference to an existing constraint:

// add a unique constraint by reference

UniqueConstraint uc = new UniqueConstraint(dt.Columns["MyColumn"]);

dt.Constraints.Add(uc);



// add a foreign key constraint by reference

ForeignKeyConstraint fc = new ForeignKeyConstraint(

    dtParent.Columns["ParentColumn"],

    dtChild.Columns["ChildColumn"]);

dt.Constraints.Add(fc);

Two overloads of the Add( ) method create and add a UniqueConstraint in one statement. The methods take a constraint name, either a reference to a DataColumn or a DataColumn array, and an argument indicating whether the column or columns are a primary key.

// add a unique constraint that is also a primary key

dt.Constraints.Add("MyUniqueConstraint", dt.Columns["MyColumn"], true);

The other two overloads of the Add( ) method create and add a ForeignKeyConstraint in one statement. The methods take a constraint name, and either two DataColumn references or two DataColumn arrays.

// add a foreign key constraint based on two columns

dt.Constraints.Add("MyForeignKeyConstraint",

    dtParent.Columns["ParentCol1"],

    dtChild.Columns["ChildCol2"]);

The AddRange( ) method adds an array of Constraint objects to the end of the constraint collection:

Constraint c1, c2;



// ... code to define constraints c1 and c2



// add the constraints c1 and c2 to the ConstraintCollection for the table

dt.Constraints.AddRange(new Constraint[] {c1, c2});