How to: Access Records in Related DataTables
When tables in a dataset are related, aobject can make available the related records in another table. For example, a dataset containing Customers and Orders tables can be made available.
You can use a DataRelation object to locate related records by calling themethod of a in the parent table; this method returns an array of related child records. Or you can call the method of a DataRow in the child table; this method returns a single DataRow from the parent table.
This Help page provides examples using typed datasets. For information on navigating relationships in untyped datasets, see.
If you are working in a Windows Forms application and using the data-binding features to display data, the designer generated form may provide enough functionality for your application. For more information, see the pages on, specifically and .
The following code examples demonstrate navigating up and down relationships in typed datasets. They use typed DataRows (NorthwindDataSet.OrdersRow) and the generated FindByPrimaryKey (FindByCustomerID) methods to locate a desired row and return the related records. The examples compile and run correctly only if you have:
An instance of a dataset named NorthwindDataSet with a Customers table
An Orders table
A relationship named FK_Orders_Customers relating the two tables available to the scope of your code
Additionally, both tables need to be filled with data for any records to be returned.
Accessing Related Records
To return the child records of a selected parent record
Call the GetChildRows method of a specific Customers data row and return an array of rows from the Orders table:
string custID = "ALFKI"; NorthwindDataSet.OrdersRow orders; orders = (NorthwindDataSet.OrdersRow)northwindDataSet.Customers. FindByCustomerID(custID).GetChildRows("FK_Orders_Customers"); MessageBox.Show(orders.Length.ToString());
To return the parent record of a selected child record
Call the GetParentRow method of a specific Orders data row and return a single row from the Customers table:
int orderID = 10707; NorthwindDataSet.CustomersRow customer; customer = (NorthwindDataSet.CustomersRow)northwindDataSet.Orders. FindByOrderID(orderID).GetParentRow("FK_Orders_Customers"); MessageBox.Show(customer.CompanyName);