System.Data Namespace DataSet Class
Sets or retrieves a value indicating whether constraint rules are followed when attempting any update operation.
Script |
DataSet.EnforceConstraints [ = true | false ] |
This property accepts or returns only a boolean value: true, if rules are enforced; otherwise, false.
The property is read/write with a default value of true.
Exception Type |
Condition |
ConstraintException |
Occurs when One or more constraints cannot be enforced. |
See the Constraints property for more details.
The following example initializes a DataSet with one table, one column, five rows, and one UniqueConstraint. The EnforceConstraints property is set to false and the values of each row are set to the same value. When the EnforceConstraints property is reset to true, a ConstraintException is generated.
private void DemonstrateEnforceConstraints ( ) {
// create a DataSet with one table, one column and a UniqueConstraint.
DataSet ds = new DataSet ( "myDataSet" );
DataTable t = new DataTable ( "myTable" );
DataColumn c = new DataColumn ( "col1" );
// a UniqueConstraint is added when the Unique property is true.
c.Unique = true;
t.Columns.Add ( c );
ds.Tables.Add ( t );
Response.Write ( "constraints.count: " + t.Constraints.Count );
// add five rows.
DataRow r ;
for ( int i=0; i < 5; i++ ) {
r = t.NewRow ( );
r [ "col1" ] = i;
t.Rows.Add ( r );
}
t.AcceptChanges ( );
ds.EnforceConstraints = false;
// change the values of all rows to 1.
foreach ( DataRow thisRow in t.Rows ) {
thisRow [ "col1" ] = 1;
// Response.Write ( "<br>" + thisRow [ 0 ] );
}
try {
ds.EnforceConstraints = true;
}
catch ( System.Data.ConstraintException ex ) {
Response.Write ( "ConstraintException: " + ex.Message );
}
catch ( System.Exception sysEx ) {
Response.Write ( sysEx.GetType ( ).Name );
Response.Write ( sysEx.Message );
}
}
Private Sub DemonstrateEnforceConstraints ( )
' create a DataSet with one table, one column and a UniqueConstraint.
Dim ds As DataSet = New DataSet ( "myDataSet" )
Dim t As DataTable = New DataTable ( "myTable" )
Dim c As DataColumn = New DataColumn ( "col1" )
c.Unique = True
t.Columns.Add ( c )
ds.Tables.Add ( t )
Response.Write ( "constraints.count: " & t.Constraints.Count )
' add five rows.
Dim r As DataRow
Dim i As Integer
For i = 0 To 4
r = t.NewRow ( )
r ( "col1" ) = i
t.Rows.Add ( r )
Next
t.AcceptChanges ( )
ds.EnforceConstraints = False
' change the values of all rows to 1.
Dim thisRow As DataRow
For Each thisRow In t.rows
thisRow ( "col1" ) = 1
Next
Try
ds.EnforceConstraints = True
Catch ex As System.Data.ConstraintException
Response.Write ( "ConstraintException: " + ex.Message )
catch sysEx As System.Exception
Response.Write ( sysEx.GetType ( ).Name );
Response.Write ( sysEx.Message );
End Try
End Sub |
|
C# |
VB |
DataSet Members Constraints ConstraintException ForeignKeyConstraint DataTable UniqueConstraint