7.6. Synchronizing Master-Detail Web Forms DataGrids

Problem

You need to create a master-detail pair of DataGrid controls and synchronize them so that when you select a record in the master, the child grid is updated with the corresponding records.

Solution

Fill a DataSet with results from both tables, and create the necessary relations before binding the DataGrid to the DataSet.

The code for the Web Forms page is shown in Example 7-11.

Example 7-11. File: ADOCookbookCS0706.aspx

<form id="ADOCookbookCS0706" method="post" runat="server">
    <asp:HyperLink id="HyperLink1"
        style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"
        runat="server" NavigateUrl="default.aspx">
        Main Menu
    </asp:HyperLink>
    <br>
    <br>
    <br>
    <asp:DataGrid id="ordersDataGrid" runat="server" PageSize="5"
        AllowPaging="True">
        <SelectedItemStyle BackColor="#80FF80"></SelectedItemStyle>
        <AlternatingItemStyle BackColor="#FFFF99"></AlternatingItemStyle>
        <Columns>
            <asp:ButtonColumn Text="Detail" CommandName="Select">
            </asp:ButtonColumn>
        </Columns>
    </asp:DataGrid>
    <br>
    <br>
    <asp:DataGrid id="orderDetailsDataGrid" runat="server" PageSize="2"
        AllowPaging="True" Width="200px">
        <AlternatingItemStyle BackColor="#FFFF99"></AlternatingItemStyle>
    </asp:DataGrid>
</form>

The code-behind file contains four event handlers and a single method:

Page.Load

Calls the CreateDataSource( ) method and binds the parent data to the parent Web Forms DataGrid, if the page is being loaded for the first time.

CreateDataSource( )

This method fills a

Get ADO.NET 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.