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
DataTable
objDtOrder = DataSet1.Tables["Order"];
DataRelation
objRelation = objDtOrder.ParentRelations[0];
DataRow
parentRow;
foreach
(DataRow row in
objDtOrder.Rows)
{
parentRow =
row.GetParentRow(objRelation);
Console.Write("\child row: " + row[1]);
Console.Write("\parent row: " + parentRow[1] + "\n");
}
Following code sample shows working of GetChildRows method
DataRow[] arrRows;
foreach
(DataRelation myRelation in myTable.ChildRelations)
{
foreach
(DataRow myRow in
myTable.Rows)
{
arrRows = myRow.GetChildRows(myRelation);
//
Print values of rows.
for
(int i = 0; i < arrRows.Length; i++)
{
foreach (DataColumn myColumn in myTable.Columns)
{
Console.WriteLine(arrRows[i][myColumn]);
}
}
}
}
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
DataRelation
relation = null;
DataRow[]
arrRows = null;
DataRow
row = null;
int
i = 0;
DataColumn
column = null;
foreach
(DataRelation objRelation in objTable.ParentRelations)
{
relation = objRelation;
foreach
(DataRow objRow in
objTable.Rows)
{
row = objRow;
arrRows = row.GetParentRows(relation);
//
Print values of rows.
for
(i = 0; i <= arrRows.GetUpperBound(0); i++)
{
foreach (DataColumn objColumn in objTable.Columns)
{
column = objColumn;
Console.WriteLine(arrRows[i][column.ColumnName]);
}
}
}
}