Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

DataTable.Constraints Property

Gets the collection of constraints maintained by this table.

Namespace:  System.Data
Assembly:  System.Data (in System.Data.dll)
public ConstraintCollection Constraints { get; }

Property Value

Type: System.Data.ConstraintCollection
A ConstraintCollection that contains the collection of Constraint objects for the table. An empty collection is returned if no Constraint objects exist.

A ForeignKeyConstraint restricts the action performed when a value in a column (or columns) is either deleted or updated. Such a constraint is intended to be used with primary key columns. In a parent/child relationship between two tables, deleting a value from the parent table can affect the child rows in one of the following ways.

  • The child rows can also be deleted (a cascading action).

  • The values in the child column (or columns) can be set to null values.

  • The values in the child column (or columns) can be set to default values.

  • An exception can be generated.

A UniqueConstraint becomes active when attempting to set a value in a primary key to a non-unique value.

The following example adds a ForeignKeyConstraint to the collection of constraints.

private void CreateConstraint(DataSet dataSet, 
    string table1, string table2, string column1, string column2)
{
    ForeignKeyConstraint idKeyRestraint = new 
        ForeignKeyConstraint(dataSet.Tables[table1].Columns[column1],
        dataSet.Tables[table2].Columns[column2]);

    // Set null values when a value is deleted.
    idKeyRestraint.DeleteRule = Rule.SetNull;
    idKeyRestraint.UpdateRule = Rule.Cascade;

    // Set AcceptRejectRule to cascade changes.
    idKeyRestraint.AcceptRejectRule = AcceptRejectRule.Cascade;

    dataSet.Tables[table1].Constraints.Add(idKeyRestraint);
    dataSet.EnforceConstraints = true;
}

.NET Framework

Supported in: 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.