O'Reilly logo

ADO.NET in a Nutshell by Bill Hamilton, Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required