
uppose you are asked to write an ASP.NET search page that performs a database search and displays the resultsemployee 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 terminologywhere 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 placesuch as a middle tier.