8.4. Displaying Hierarchical Data with LINQ

A LINQ query can organize data in groups or categories for display in the ASP.NET GridView control. In this section, you create a page like Figure 8-4, in which the products for the Northwind database appear according to their category, such as Beverages.

Figure 8-4. Display products in categories.

8.4.1. Grouping with a LINQ query

In this example, you create the LINQ query in code rather than in a LinqDataSource control. Listing 8-1 shows all the code you need to create groups of products according to their categories. The code assumes that you create the DataContext objects as explained in the earlier section, "Creating the database access code." Follow these steps to create a page to use the query:

  1. Add an ASP.NET page named hierar.aspx to your project.

  2. In Design view, double-click an empty area of the page to create a handler for the Page Load event.

  3. Within the Page_Load() subroutine, add the contents of Listing 8-1.

You create the user interface for hierar.aspx in subsequent steps. First, do a walk-through of Listing 8-1 to understand the query and its groups.

Listing 8-1. Grouping by Categories with LINQ's Group By
Dim dc As New NWDataClassesDataContext Dim q = From c In dc.Categories, _ p In dc.Products _ Where c.CategoryID = p.CategoryID _ Group p By c.CategoryName Into Group _ Select New With _ {.cgname = CategoryName, _ .prdcts ...

Get ASP.NET 3.5 For Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.