O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

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

8.6. Using XPath to Query Data in a DataSet

Problem

You need to use an XPath expression to extract certain rows from a DataSet.

Solution

Use SelectSingleNode( ) or SelectNodes( ).

The sample code contains two event handlers:

Form.Load

Sets up the sample by creating a DataSet containing the Orders table and Order Details table from Northwind and a nested relation between the two tables.

Go Button.Click

Executes an XPath query to retrieve the Orders and Order Details data for an OrderID specified by the user to an XmlNode. The results are displayed by iterating over the XmlNode to retrieve the Orders and the XmlNodeList containing the Order Details.

The C# code is shown in Example 8-9.

Example 8-9. File: XPathQueryForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Text; using System.Xml; using System.Data; using System.Data.SqlClient; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE = "OrderDetails"; // Relation name constants private const String ORDERS_ORDERDETAILS_RELATION = "Orders_OrderDetails_Relation"; // Field name constants private const String ORDERID_FIELD = "OrderID"; private DataSet ds; // . . . private void XPathQueryForm_Load(object sender, System.EventArgs e) { ds = new DataSet("Orders_OrderDetails"); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); ...

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