Walkthrough: Creating a Nested GridView Control
The GridView control displays rows of data in a grid (an HTML table), displaying one data row per grid row. This walkthrough shows you how to extend the functionality of the GridView control so that individual grid rows can display data from a related data table. In the walkthrough, you show related data in a nested GridView control — a GridView control inside the grid row of the parent GridView control.
In this walkthrough, you will see how to create a GridView control that displays a list of customers where each row of the GridView control includes another GridView control that displays the orders for that customer. Both GridView controls use SqlDataSource controls to retrieve the data from the data source.
Tasks illustrated in this walkthrough include the following;
Connect to a SQL Server database in a Microsoft Visual Studio Web site project.
Use the SqlDataSource control to manage data access.
Display data returned from the database in the GridView control.
Create a TemplateField with nested controls to be displayed by the GridView control.
Dynamically customize the display for each row based on run-time conditions.
Optionally, use data caching with the SqlDataSource control to reduce requests made to the database.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Studio or Visual Web Developer Express installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web Development collection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings.
Access to the SQL Server Northwind database. For information about how to download the SQL Server sample Northwind database, see Installing Sample Databases on the Microsoft SQL Server Web site.
Creating the Web Site
If you have already created a Web site in Visual Studio (for example, by completing Walkthrough: Creating a Basic Web Forms Page in Visual Studio), you can use that Web site and go to the next section. Otherwise, create a new Web site and page.
This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects in Visual Studio.
To create a file system Web site
Open Visual Studio or Visual Web Developer Express.
In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET Empty Web Site.
In the Web location box, select File System, and then enter the name of the folder where you want to keep the pages for your Web site.
For example, type the folder name C:\WebSites\NestedGridView.
Click OK.
Visual Studio creates a Web site project that includes a Web.config file.
Adding a Data Source for the GridView Control
To display data on an ASP.NET Web page, you need the following:
A connection to a data source (such as a database). In this walkthrough, you will create a connection to the SQL Server Northwind database.
A control on the page to display the data.
In the following procedure, you will display data in a GridView control. The GridView control will get its data from the SqlDataSource control.
To add a data source for the GridView control
If your Web site does not have an App_Data folder, in Solution Explorer, right-click the Web site name, select Add ASP.NET Folder, and then click App_Data.
Copy Northwind.mdf from the following folder to your App_Data folder:
C:\SQL Server 2000 Sample Databases
If your Web site does not have a Default.aspx file, create one by performing the following steps:
In Solution Explorer, right-click the project name and then click Add New Item.
In the Add New Item dialog box, under Installed Templates select Visual C# or Visual Basic.
Select Web Form, enter Default.aspx in the Name box, and then click Add.
If Default.aspx is not open, open it.
Switch to Design view.
In the Toolbox, from the Data group, drag a SqlDataSource control onto the page.
If the SqlDataSource Tasks smart tag does not appear, right-click the SqlDataSource control and then click Show Smart Tag.
In the SqlDataSource Tasks panel, click Configure Data Source.
The Configure Data Source wizard appears.
Click New Connection.
The Add Connection dialog box appears.
If the Data source list does not display Microsoft SQL Server Database File (SqlClient), click Change, and in the Change Data Source dialog box, select Microsoft SQL Server Database File.
If the Choose Data Source dialog box appears instead of the Connection Properties dialog box, in the Data source list, select Microsoft SQL Server Database File. In the Data provider list, make sure .NET Framework Data Provider for SQL Server is selected, and then click Continue.
In the Add Connection dialog box, click Browse, navigate to the App_Data folder of the project you are working on, and select the Northwind.mdf file.
Click OK.
In the Choose Your Data Connection wizard step, click Next.
In the Save the Connection String to the Application Configuration File step, make sure that the Yes, save this connection as check box is selected.
Name the connection NorthwindConnectionString and then click Next.
In the Configure the Select Statement step, select Specify columns from a table or view.
In the Name list, select Customers.
In the Columns list, select the CustomerID and CompanyName columns.
Click Next.
Click Finish.
Adding a GridView Control to Display Data
After you have established a data source to retrieve the data, you must add a control to the page to display the data.
In the following procedure, you will display data in a GridView control. The GridView control will get its data from the SqlDataSource control that you added previously.
To add and configure a GridView control for displaying data
Ensure that you are in Design view for the Default.aspx page.
In the Toolbox, from the Data group, drag a GridView control onto the page.
Click the smart tag to show the GridView Tasks panel.
In the Choose Data Source list, select the SqlDataSource control that you added previously (SqlDataSource1).
Select the Enable Paging check box.
In the Properties window, expand the RowStyle property for the GridView control, and then set the VerticalAlign property to Top. This will align the text in the grid row at the top of the cells, because the nested grid will display multiple lines.
Adding a Nested GridView Control to Display Related Data
You will now create a nested data source and GridView control to display related data in each row. To do so, you will do the following:
Create a TemplateField for the rows displayed by the GridView control.
Add a nested GridView control and SqlDataSource control to the TemplateField element to display related data for individual rows.
Add a procedure to handle the RowDataBound event of the parent GridView control in order to set the select parameter value for the nested SqlDataSource control.
To add and configure a nested GridView control for displaying data
Ensure that you are in Design view for the Default.aspx page.
Click the GridView control, and then click the smart tag.
In the GridView Tasks panel, click Edit Columns.
The Fields dialog box appears.
In the Available fields panel, select TemplateField, and then click Add.
In the TemplateField properties panel, set HeaderText to Orders.
Click OK.
In the GridView Tasks panel, click Edit Templates.
In Template Editing Mode panel, from the Display list, select ItemTemplate.
In the Toolbox, from the Data group, drag a SqlDataSource control onto the page to the editable area of the ItemTemplate element.
In the SqlDataSource Tasks panel, click Configure Data Source.
The Configure Data Source wizard appears.
For the Choose Your Data Connection step, select the NorthwindConnectionString option that you created earlier in this walkthrough and then click Next.
In the Configure the Select Statement step, select Specify columns from a table or view.
In the Name list, select Orders.
In the Columns panel, select the OrderID and OrderDate columns.
Click WHERE to add a parameter for the SELECT statement.
In the Add WHERE Clause window, select CustomerID in the Column list.
Select None in the Source list.
Click Add.
This creates a select parameter that you will set to the CustomerID value for each row that is bound to the parent GridView control.
Click OK.
Click Next.
Click Finish.
In the Toolbox, from the Data group, drag a GridView control to the editable area of the ItemTemplate.
Click the GridView smart tag, and then in the Choose Data Source list, select the name of the nested SqlDataSource control (SqlDataSource2).
Right-click the parent GridView control (GridView1) and then click Show Smart Tag.
In the GridView Tasks panel, click End Template Editing.
Note
The nested GridView control is not displayed in Design view.
In the Properties window for GridView1, click the Events button ().
Double-click inside the value box for RowDataBound.
Visual Studio creates an event handler for the RowDataBound event of the GridView control. The code will resemble the following example:
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound End Sub
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { }
Inside the skeleton event handler, add the following code:
If e.Row.RowType = DataControlRowType.DataRow Then Dim s As SqlDataSource = CType(e.Row.FindControl("SqlDataSource2"), SqlDataSource) s.SelectParameters(0).DefaultValue = e.Row.Cells(0).Text End If
if (e.Row.RowType == DataControlRowType.DataRow) { SqlDataSource s = (SqlDataSource)e.Row.FindControl("SqlDataSource2"); s.SelectParameters[0].DefaultValue = e.Row.Cells[0].Text; }
The code retrieves the CustomerID value for the current row and sets it as the select parameter value for the nested SqlDataSource control (SqlDataSource2).
Save the changes to the files.
Testing the Page
You can now run the page.
To test the page
Press CTRL+F5 to run the page.
The GridView control displays the data rows from the Northwind Customers table with data from the Northwind Orders table for each customer nested in each row.
Close the browser.
Using Caching with a Nested GridView Control
At this point in the walkthrough, you have created a page with nested GridView controls. As currently written, the page queries the database one time for the parent GridView control, and again for each nested GridView control.
To reduce database load, you can modify your nested query to return all rows, cache the results, and then filter the results for each nested GridView control.
Note
For large databases, this is not a practical solution. If you are retrieving data from a large database, build a data object that retrieves only the required rows and bind to it using the ObjectDataSource control. For more information, see ObjectDataSource Web Server Control Overview.
To configure a nested SqlDataSource control to cache query results
In the Default.aspx page, switch to Design view.
In the smart tag panel for the GridView1 control, click Edit Templates.
In the ItemTemplate element for the Orders column, select the nested SqlDataSource control (SqlDataSource2).
In the Properties window, set the EnableCaching property to true.
Set the FilterExpression property to CustomerID='{0}'.
In the FilterParameters property, click the ellipsis button () to open the Parameter Collection Editor window.
In the Parameter Collection Editor window, click Add Parameter.
In the Name box, enter CustomerID.
Click OK.
Right-click the nested SqlDataSource control (SqlDataSource2) and then click Show Smart Tag.
In the smart tag panel, click Configure Data Source.
Leave the connection information unchanged and click Next.
In the Configure the Select Statement step, select Specify columns from a table or view.
In the Name list, select Orders.
In the Columns section, check the OrderID, CustomerID, and OrderDate columns, and then click Next.
Click Finish.
When you are prompted to refresh the fields and keys for the GridView2 control, click No.
The columns displayed by the nested GridView control will not change.
You have configured the nested SqlDataSource control to retrieve all the order data from the database and cache it locally. When the nested GridView control is bound to the data, a filter is applied so that only orders related to the CustomerID value for the current row are displayed.
If you are using a code-behind page, right-click a blank area on the page, and then click View Code.
Change the code for the RowDataBound event handler to read as follows:
If e.Row.RowType = DataControlRowType.DataRow Then Dim s As SqlDataSource = CType(e.Row.FindControl("SqlDataSource2"), SqlDataSource) s.FilterParameters(0).DefaultValue = e.Row.Cells(0).Text End If
if (e.Row.RowType == DataControlRowType.DataRow) { SqlDataSource s = (SqlDataSource)e.Row.FindControl("SqlDataSource2"); s.FilterParameters[0].DefaultValue = e.Row.Cells[0].Text; }
In this version of the code, instead of setting a value in the SqlDataSource control's SelectParameters collection, you set a value in its FilterParameters collection.
Save the file.
Testing the Page
You can now run the page.
To test the page
Press CTRL+F5 to run the page.
The GridView control displays the data rows from the Northwind Customers table with data from the Northwind Orders table for each customer nested in each row. However, all the data that is bound to the GridView control will be requested one time, when the first row is data bound. The data is cached for use with the remaining rows of the GridView control.
Close the browser.
Next Steps
This walkthrough has illustrated how you can extend the functionality of the GridView control to display related data by using nested GridView controls on an ASP.NET Web page. You can also extend your application to enable data to be updated and deleted or to enable users to insert new records by using a DetailsView or FormView control. You might also use controls other than a TextBox control, such as a DropDownList control, to change a value. For more information, see the following topics:
Walkthrough: Creating Master/Detail Web Pages in Visual Studio
Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control
See Also
Tasks
How To: Secure Connection Strings when Using Data Source Controls
Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control
Walkthrough: Basic Data Access Using the SqlDataSource Control in Web Pages