Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCreate a foreign key constraint between two DataTables in VB .NET
DescriptionThis example shows how to create a foreign key constraint between two DataTables in VB .NET.
KeywordsDataSet, VB.NET, data, database, ADO.NET, foreign key, constraint
CategoriesDatabase, VB.NET
 
First, create a DataSet and DataAdapters to load the data. See the example Display the data in a DataSet by using as DataGrid control in VB .NET for instructions.

When the program starts, the Form_Load event handler uses the following code to create the constraint and load the data into the DataSet. It first gets references to the Students and Scores DataTables in the DataSet. It then adds a new constraint to the Scores DataTable. It names the constraint FKScoresStudents and passes in column objects representing the columns that should be related. The routine finishes by loading the data into the DataSet.

 
' Load the DataSet.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    ' Make the foreign key constraint. This means you
    ' cannot add
    ' a Scores record unless the StudentID exists in the
    ' Students table.
    Dim dt_students As DataTable = _
        dsTestScores.Tables("Students")
    Dim dt_scores As DataTable = _
        dsTestScores.Tables("Scores")
    dt_scores.Constraints.Add("FKScoresStudents", _
        dt_students.Columns("StudentID"), _
        dt_scores.Columns("StudentID"))

    ' Load the data.
    daStudents.Fill(dsTestScores)
    daScores.Fill(dsTestScores)
End Sub
 
After the constraint has been added, the DataSet will not let you violate it. In this example, that means you cannot add a Scores record unless its StudentID value is already in the Students table.

For more information on database programming in VB .NET, see my book Visual Basic .NET Database Programming.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated