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
Form1design surface:DataGridViewnamedheaderDataGridViewDataGridViewnameddetailDataGridView
The completed layout of the Windows Form named
Form1is 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access