JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating a Data Relation Object in Code

In Chapter 21, the ParentChildData example used the publishers and titles tables in the pubs database and related them through the pub_id key. This example displayed the publishers.pub_name field in the combo box you see in Figure 21.12, and when the user selected a publisher, the program displayed all that publisher's books in the datagrid below. In that chapter, we created a data relation object visually, but now we'll see how to do the same thing by creating a DataRelation object in code, as shown in the ParentChildDataCode example on the CD-ROM.

To create the new DataRelation object, I just pass this object's constructor the name of the new object, the parent column, and the child column. Then I add the new relation object to a dataset's Relations collection, and bind a data grid to that object, like this:

Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

    Dim PublishersColumn As DataColumn
    Dim TitlesColumn As DataColumn

    PublishersColumn = DataSet11.Tables("publishers").Columns("pub_id")
    TitlesColumn = DataSet11.Tables("titles").Columns("pub_id")

    Dim publisherstitles As DataRelation
    publisherstitles = New DataRelation("publisherstitles", _
        PublishersColumn, TitlesColumn)

    DataGrid1.SetDataBinding(DataSet11, "publishers.publisherstitles")
End Sub

This creates the same master/detail connection that the ParentChildData example gave us in Chapter 21. You can see this example, ParentChildDataCode, at work in Figure 22.6 (compare it to Figure 21.12).

Click To expand
Figure 22.6: Using a data relation object.
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor