How to Retrieving Parent and Child DataTable Records

How to Retrieving Parent and Child DataTable Records

It's easy to retrieve data that capitalizes on relationship after establishing a parent-child relationship between two tables in a DataSet. The DataRow class includes two methods— GetChildRows and GetParentRow—that retrieve the relevant row(s) at the other end of a linked relationship. Because a column could be involved in multiple relationships, you must pass either the name or the instance of the relationship to the relevant method.

 Following code sample shows working of GetParentRow method

 

        Dim objDtOrder As DataTable = DataSet1.Tables("Order")

        Dim objRelation As DataRelation = thisTable.ParentRelations(0)

        Dim parentRow As DataRow

        Dim row As DataRow

        For Each row In objDtOrder.Rows

            parentRow = row.GetParentRow(objRelation)

            Console.Write(ControlChars.Tab & " child row: " _

               & row(1).ToString())

            Console.Write(ControlChars.Tab & " parent row: " _

               & parentRow(1).ToString() & ControlChars.Cr)

        Next row

 

Following code sample shows working of GetChildRows method

 

        Dim myRelation As DataRelation

        Dim arrRows() As DataRow

        Dim myRow As DataRow

        Dim i As Integer

        Dim myColumn As DataColumn

 

        For Each myRelation In myTable.ChildRelations

            For Each myRow In myTable.Rows

                arrRows = myRow.GetChildRows(myRelation)

                For i = 0 To arrRows.GetUpperBound(0)

                    For Each myColumn In myTable.Columns

                        Console.WriteLine(arrRows(i)(myColumn))

                    Next myColumn

                Next i

            Next myRow

        Next myRelation

 

 

The DataRow class also includes a method named GetParentRows that returns multiple parent rows for a single child record. This is useful for parent-child relationships that are linked on columns other than the parent's primary key.

 

Following code sample shows working of GetParentRows method

 

        Dim objRelation As DataRelation

        Dim arrRows() As DataRow

        Dim objRow As DataRow

        Dim i As Integer

        Dim objColumn As DataColumn

 

        For Each objRelation In objTable.ParentRelations

            For Each objRow In objTable.Rows

                arrRows = objRow.GetParentRows(objRelation)

                ' Print values of rows.

                For i = 0 To arrRows.GetUpperBound(0)

                    For Each objColumn In objTable.Columns

                        Console.WriteLine(arrRows(i)(objColumn.ColumnName))

                    Next objColumn

                Next i

            Next objRow

        Next objRelation