Create a Calculated Column That Uses a Relationship

Problem

You want to add a calculated column to a parent table that displays information from a child table.

Solution

Create a new DataColumn for the parent table. Set the DataColumn.Expression property to count or sum information from the related rows.

Discussion

You can create a simple calculated column by instantiating a new DataColumn object, setting its Expression property, and adding it the DataTable.Columns collection for the appropriate table. For example, the following code creates a column that multiplies the information from two other columns:

Dim Col As New DataColumn("InventoryValue", GetType(Decimal), _
  "UnitPrice * UnitsInStock")
Ds.Tables(0).Columns.Add(Col)

When writing the expression, ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.