O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required