Navigating Relational Data

Once a relation is established, you can use it navigate from a parent row to the associated child rows or from a child row to the parent. Use the GetChildRows( ) or GetParentRow( ) method of the DataRow object:

foreach (DataRow parent in ds.Tables["Categories"].Rows)

{

    // (Process the category row.)



    foreach (DataRow child in parent.GetChildRows("Cat_Prod"))

    {

        // (Process the products in this category.)

    }

}

Similarly, the reverse logic branches from a child to the related parent:

foreach (DataRow child in ds.Tables["Products"].Rows)

{

    // (Process the product row.)



    DataRow parent = child.GetParentRow("Cat_Prod");

    // (Process category for this product.)

}

This syntax presents an easy and elegant way to traverse hierarchical data. However, it isn’t the only way to handle relational data. You can simply use the DataTable.Select( ) method to extract matching rows from another table. The Select( ) method returns an array of DataRow objects based on a SQL expression (and optionally the DataViewRowState). For example, to traverse relational data, use the Select( ) method to retrieve rows from the child table that match the parent’s key field. It’s a little more work, but accomplishes the same task without requiring a DataRelation.

foreach (DataRow parent in ds.Tables["Categories"].Rows) { // (Process the category row.) DataRow[] rows = ds.Tables["Products"].Select("CategoryID=" + parent["CategoryID"].ToString()); foreach (DataRow row in rows) { // (Process the ...

Get ADO.NET in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.