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