8.17. Synchronizing Master-Detail Data in a Windows Forms Application
Problem
You need to bind both a parent table and child table within a DataSet
to a pair of DataGridView
controls so that the child data is displayed when a parent is selected.
Solution
Create a BindingSource
for both the parent and detail DataGridView
controls. Set the DataSource
and DataMember
properties of the parent BindingSource
to specify the parent result set. Set the DataSource
of the child BindingSource
to the parent BindingSource
and DataMember
of the child BindingSource
to the name of the data relation between the parent and child tables.
Follow these steps:
Create a C# Windows Forms application,
MasterDetailWindowsFormDataGrid
.Add the following controls to the
Form1
design surface:DataGridView
namedheaderDataGridView
DataGridView
nameddetailDataGridView
The completed layout of the Windows Form named
Form1
is shown in Figure 8-33.
Figure 8-33. Layout for Form1 in MasterDetailWindowsFormDataGrid solution
The C# code in Form1.cs in the project MasterDetailWindowsFormDataGrid
is shown in Example 8-29. The solution creates a DataSet
containing a subset of the Sales.SalesOrderHeader
and Sales.SalesOrderDetail
records from AdventureWorks
and a DataRelation
named FK_SalesOrderDetail_SalesOrderHeader
relating the two tables. A BindingSource
is created for both the parent and detail DataGridView
controls named headerBindingSource ...
Get ADO.NET 3.5 Cookbook, 2nd Edition 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.