How to: Create Master-Details Lists with the Windows Forms DataGrid Control Using the Designer

Note

The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. For more information, see Differences Between the Windows Forms DataGridView and DataGrid Controls.

If your DataSet contains a series of related tables, you can use two DataGrid controls to display the data in a master-detail format. One DataGrid is designated to be the master grid, and the second is designated to be the details grid. When you select an entry in the master list, all of the related child entries are shown in the details list. For example, if your DataSet contains a Customers table and a related Orders table, you would specify the Customers table to be the master grid and the Orders table to be the details grid. When a customer is selected from the master grid, all of the orders associated with that customer in the Orders table would be displayed in the details grid.

The following procedure requires a Windows Application project (File > New > Project > Visual C# or Visual Basic > Classic Desktop > Windows Forms Application).

To create a master-details list in the designer

  1. Add two DataGrid controls to the form. For more information, see How to: Add Controls to Windows Forms. In Visual Studio 2005, the DataGrid control is not in the Toolbox by default. For more information, see How to: Add Items to the Toolbox.

    Note

    The following steps are not applicable to Visual Studio 2005, which uses the Data Sources window for design-time data binding. For more information, see Bind controls to data in Visual Studio and How to: Display Related Data in a Windows Forms Application.

  2. Drag two or more tables from Server Explorer to the form.

  3. From the Data menu, select Generate DataSet.

  4. Set the relationships between the tables using the XML Designer. For details, see "How to: Create One-to-Many Relationships in XML Schemas and Datasets" on MSDN.

  5. Save the relationships by selecting Save All from the File menu.

  6. Configure the DataGrid control that you want to designate the master grid, as follows:

    1. Select the DataSet from the drop-down list in the DataSource property.

    2. Select the master table (for example, "Customers") from the drop-down list in the DataMember property.

  7. Configure the DataGrid control that you want to designate the details grid, as follows:

    1. Select the DataSet from the drop-down list in the DataSource property.

    2. Select the relationship (for example, "Customers.CustOrd") between the master and detail tables from the drop-down list in the DataMember property. In order to see the relationship, expand the node by clicking on the plus (+) sign next to the master table in the drop-down list.

See also