Adding a relationship between DataTables

A DataTable can be related to another DataTable in the same DataSet using DataRelation object. Using DataRelation the navigation between DataTable (foreign key connection) becomes very easy.

An example for using Child Relation is located here:

Here is an example for using Parent Relation:

We have two DataTables: DataTableOrder (OrderId is foreign key to DataTableOrderDetails) and DataTableOrderDetails (Id is primary key)

//create dataset
DataSet dataSet = new DataSet();

//add existing tables to the DataSet
dataSet.Tables.Add(DataTableOrder );

// create relation between both tables

foreach (DataRow row in DataTableOrder .Rows)
//get parent rows using relation - all order details for current order
//use GetParentRows for relations 1 to many
DataRow dr=row.GetParentRow(dtm.ParentRelations[0]);
//check if there is a parent row
Response.Write(row["OrderName"].ToString() +"->"+ dr["OrderDetails"].ToString() +"

1 comment:

  1. At last, i found. Thank you very much indeed!