|
|
Title | Create a foreign key constraint between two DataTables in VB .NET |
Description | This example shows how to create a foreign key constraint between two DataTables in VB .NET. |
Keywords | DataSet, VB.NET, data, database, ADO.NET, foreign key, constraint |
Categories | Database, 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.
|
|
|
|
|
|