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:
http://msdn.microsoft.com/en-us/library/system.data.datatable.childrelations.aspx

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 );
dataSet.Tables.Add(DataTableOrderDetails);

// create relation between both tables
dataSet.Relations.Add(
dataSet.Tables[1].Columns["Id"],
dataSet.Tables[0].Columns["OrderId"]);

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
if(dr!=null){
Response.Write(row["OrderName"].ToString() +"->"+ dr["OrderDetails"].ToString() +"
")
}
}

1 comment:

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

    ReplyDelete