Displaying Master-Details Relationships in ASP.NET 2.0by Wei-Meng Lee
One of the common tasks in manipulating databases is displaying master-details relationships. A very good example is the SQL Server 2000 sample database pubs, which contains several interrelated tables. The authors table is related to the titles table through the titleauthor table (see Figure 1).
Figure 1. The relationships between the authors, titleauthor, and the titles tables in the pubs database
In this article, I will show you how you can use the GridView and DetailsView controls to display records in the authors and titles tables.
Displaying the Master
Using Visual Studio 2005, create a new web site project and name it MasterDetails. Drag the GridView control from the Toolbox and drop it onto default.aspx. In the GridView's Smart tag, select the Choose Data Source drop-down list and select <New Data source…> (see Figure 2).
Next, follow these steps:
Figure 2. Configuring a data source for the GridView control
- In the Data Source Configuration Wizard dialog, choose Database and click OK.
- You will now be asked to choose a connection to the desired database. Click the New Connection... button to choose your database.
- In the Add Connection dialog, you have the option to choose the different types of databases that you can use for your project. Click the Change… button and select Microsoft SQL Server.
- For the Server name entry, enter ".\SQLEXPRESS" (assuming that you have installed the SQL Server 2005 Express edition database on your local computer). Select the pubs database (see Figure 3). Again, I am assuming that you have the pubs sample database installed on your computer. Click OK.
- You will now be asked to save the connection string information in the application configuration file. Click Next.
- In the next dialog, select the authors table and select all its fields (see Figure 4). Click Next.
- You can now preview the content of the selected table by clicking on the Test Query button (see Figure 5). Click Finish.
Figure 3. Selecting the database server and database name
Figure 4. Specifying the table and its fields
Figure 5. Previewing the content of the authors table