Microsoft KB Archive/319413

= Incorrect DataRelation.ChildKeyConstraint property example =

Article ID: 319413

Article Last Modified on 9/15/2005

-

APPLIES TO


 * Microsoft ADO.NET 1.1
 * Microsoft ADO.NET 1.0
 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-



This article was previously published under Q319413



SUMMARY
In the MSDN Library Topic DataRelation.ChildKeyConstraint Property and in the Visual Studio Help topic &quot;DataRelation.ChildKeyConstraint Property,&quot; the sample code is incorrect. The Help Topics describe how to obtain the ForeignKeyConstraint for the relation.

The sample code is incorrect because it creates a DataRelation object and then tries to get the ForeignKeyConstraint object from its ChildKeyConstraint property immediately after that. The following code is an example of the incorrect sample code: Private Sub SetChildKeyConstraint(ds As DataSet)

Dim dr As DataRelation Dim cCol As DataColumn Dim pCol As DataColumn ' Set child and parent columns. pCol = ds.Tables(&quot;Suppliers&quot;).Columns(&quot;SupplierID&quot;) cCol = ds.Tables(&quot;Products&quot;).Columns(&quot;SupplierID&quot;) dr = New DataRelation(&quot;SuppliersConstraint&quot;, pCol, cCol) Dim fk As ForeignKeyConstraint = dr.ChildKeyConstraint fk.DeleteRule = Rule.SetNull fk.UpdateRule = Rule.Cascade fk.AcceptRejectRule = AcceptRejectRule.Cascade

End Sub If you run the code, a System.NullReferenceException is thrown and you receive the following error message:

Object reference not set to an instance of an object.

CAUSE
The ChildKeyConstraint property of the DataRelation is not instantiated unless you add the DataRelation object to the DataSet first.

RESOLUTION
Before you access the Constraints of a DataRelation object, add the DataRelation object to the relations collection of the DataSet. The correct code sample is as follows:

Private Sub SetChildKeyConstraint(ds As DataSet)

Dim dr As DataRelation Dim cCol As DataColumn Dim pCol As DataColumn ' Set child and parent columns. pCol = ds.Tables(&quot;Suppliers&quot;).Columns(&quot;SupplierID&quot;) cCol = ds.Tables(&quot;Products&quot;).Columns(&quot;SupplierID&quot;) dr = New DataRelation(&quot;SuppliersConstraint&quot;, pCol, cCol) ds.Relations.Add(dr)

Dim fk As ForeignKeyConstraint = dr.ChildKeyConstraint fk.DeleteRule = Rule.SetNull fk.UpdateRule = Rule.Cascade fk.AcceptRejectRule = AcceptRejectRule.Cascade

End Sub

Keywords: kbbug kbdocerr kbpending kbvs2002sp1sweep KB319413

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.