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

2.17. Displaying Columns from a Related DataTable

Problem

You want to add a column to a DataTable that displays a value from a row in a related table in the DataSet.

Solution

Use expression columns to retrieve lookup values based on DataRelation objects.

The sample code creates a new DataSet containing the Orders table and the Order Details table from Northwind. A DataRelation is created between the tables. A column is added to the Order Details table that gets the CustomerID from the parent Order using the relation created between the tables. Finally, the default view of the Orders table is bound to the data grid on the form.

The C# code is shown in Example 2-22.

Example 2-22. File: LookupColumnsForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; 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 const String CUSTOMERID_FIELD = "CustomerID"; private const String QUANTITY_FIELD = "Quantity"; // . . . DataSet ds = new DataSet( ); // Fill the Orders table and add it to the DataSet. SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders", ConfigurationSettings.AppSettings["Sql_ConnectString"]); DataTable ordersTable = new DataTable(ORDERS_TABLE); ...

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