13.6 Navigating Hierarchical Data

The strongly typed DataSet provides two methods for each DataRelation , TableName Row( ) and TableName Rows( ) , to facilitate navigating records in parent child relationships. These methods are similar to the GetParentRow( ) and GetChildRows( ) methods in the untyped DataSet . The TableName Row( ) method is defined for the child table and retrieves the parent row for a DataRow . The TableName Rows( ) method is defined for the parent table in a relationship and retrieves the child rows for a DataRow .

The strongly typed DataSet methods encapsulate the DataRelations defined within the DataSet so a reference to the DataRelation or the name of the DataRelation isn't required when navigating the hierarchy of records. The following sample demonstrates using the strongly typed DataSet methods to navigate a hierarchy of records:

 // strongly typed DataSet called Northwind containing Orders table and  // OrderDetails table, related through the OrderID field Northwind ds = new Northwind(); // ... code to fill the Orders and Order Details tables in the DataSet foreach(Northwind.OrdersRow ordersRow in ds.Orders) {     // iterate the collection of order details for the order through     // the GetOrderDetailsRow accessor     foreach(Northwind.Order_DetailsRow orderDetailsRow in         ordersRow.GetOrder_DetailsRows())     {         // get the CustomerID from the parent row, through the         // OrdersRow property of the child row         String customerId = orderDetailsRow.OrdersRow.CustomerID;                  // get the ProductID         Int32 productId = orderDetailsRow.ProductID;     } } 

This example shows comparable code using an untyped DataSet :

 // untyped DataSet containing Orders table and  // OrderDetails table, related through the OrderID field DataSet ds = new DataSet(); // ... code to define or retrieve the schema for the Orders and // [Order Details] tables schemas including creating DataRelation objects // ... code to add new rows to the Orders and [Order Details] tables foreach(DataRow ordersRow in ds.Tables["Orders"].Rows) {     foreach(DataRow orderDetailsRow in         ordersRow.GetChildRows("Order_OrderDetails"))     {         // get the CustomerID from the parent row         String customerId  =               orderDetailsRow.GetParentRow("Order_OrderDetails")             ["CustomerID"].ToString();                  // get the ProductID         Int32 productId = (Int32)orderDetailsRow["ProductID"];             } } 


ADO. NET in a Nutshell
ADO.NET in a Nutshell
ISBN: 0596003617
EAN: 2147483647
Year: 2005
Pages: 415

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net