RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Nested DataGrids Simplify Hierarchical Data Display

Learn how to use nested DataGrids to display hierarchical data and avoid the maintenance nightmare of dynamically-created HTML tables.

uppose you are asked to write an ASP.NET search page that performs a database search and displays the results—employee names, recent project assignments for each, and hours billed per week per assignment. Would you approach the task by dynamically constructing HTML tables in a code-behind page using code such as Label.Text = "<td>" + … + "</td>"? Or would you instead create table Web controls dynamically at run-time? Either way, don't do it! There's a better approach. Nesting multi-record controls such as DataGrids, GridViews, DataRepeaters, or DataLists is not as hard as you might think and offers numerous benefits compared to more traditional approaches.

Using these techniques does require a solid understand of ASP.NET binding techniques such as the data-binding syntax, the hierarchy of data-bound Web controls, and the event model for Web controls. This article reviews these concepts in the context of nested, data-bound, multi-record Web controls and examines a fully-commented, downloadable Northwind solution that accompanies this article (see Figure 1).

Figure 1. Orders Advanced Search Screenshot: Three nested loops in the sample application display orders, products, and historical order counts based on the dates users enter into the Date Range fields.
DataSource, DataBinding, DataSets, Oh My!
If you find yourself confused by.NET terminology—where it sometimes seems as if every word starts with "Data"—you aren't alone. This section attempts to clarify and differentiate the terms while also providing you with a method to approach the problem of displaying hierarchical data.

Early Data Equals Better Data
A naïve approach to displaying hierarchical data would be to retrieve the data just before you need it in the presentation tier, for example:

   get data from database
   for each row {
       get more data from database based on the current row
       for each new row {
           create controls or Response.Write()

Opening database connections inside of loops as in the preceding code isn't always a mistake, but it's rarely the best approach. Furthermore, the preceding code combines display elements and looping logic in the same place. In contrast, retrieving the data for all the loops before dealing with the UI provides two attractive benefits. First, it can lead to significantly better performance because it avoids the overhead of opening database connections inside loops. Second, it lets you separate data retrieval code and put it in a common place—such as a middle tier.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date