Build a Nested GridView Control with ASP.NET

The biggest oversight in ASP.NET is the lack of an easy way to create fully functional nested grid and user control views (nested means one or more controls exist in one or more GridView cells; these controls may be grids or user control grids nested n-levels deep.) Propagating data downstream, permitting full editing functionality, and event handling are still very labor intensive. This is a glaring deficiency in the way you can develop Web applications with ASP.NET.

Suppose you want to show customers, orders, order details, and maybe product information from a Northwind database in a related way. The mechanically easy way to derive such a presentation is to establish links between pages and have each subsequent page zoom in to a related downstream piece of information. To put it mildly, this type of implementation results in a tedious series of clicking, posting, and page navigation. (Even with the asynchronous capabilities of Atlas, all of the required clicking can be cumbersome.) Worse still, editing can be a nightmare with partial state changes and database modifications.

This article demonstrates how to take the first step towards making n-dimensionally complex ASP.NET presentations, vastly reducing the number of round trips, and greatly improving data management. You will see how to create complex views easily. (In reality, though, this is something Microsoft should address. They easily could use the implementation style in this article to take the tedium out of building complex GUIs in ASP.NET.)

The objective is simple: Show all of the orders for each customer in a single page (see Figure 1). (The demonstration is not interested in "prettification"; with a style sheet, you could easily dress up the view.)

Figure 1: A Nested GridView Control Showing Customers and Orders

Building a Master Detail View Using the GridView

Due to space constraints, this article shows only two levels of nesting. However, by the time you are done, you will see that this approach works for n levels of nesting. The only caution is that with very complex presentation styles bandwidth can become an issue.

Tip: If you want a nicely color-coordinated Web application, try Behr's Smart Color tool. It will help you pick a perfectly coordinated, tri-chromatic color palette. Tell them I sent you.

Reviewing the Constituent Parts of the Page

Each level of nesting is composed of three basic parts:

  • A page or user control, which basically are the same thing for this demo's purposes
  • A GridView (or some other similar type control)
  • A UserControl, which will be used to contain the nested elements
  • The nested controls to implement the UserControl (these can be individual controls or another GridView)

At the highest level of the nested view is an ASP.NET Web Page. The page is important not only because it will be the root of the presentation layer, but it also is where user data will be stored in session and where changes will be persisted.

The page-level GridView simply repeats and displays the data at the highest level of the relationship. (It is ultimately rendered as an HTML table.)

At every subsequent level of nesting, you will use a UserControl—an important element that enables you to divide up pieces of the presentation into manageable parts. The UserControl essentially provides a blank canvas that you can use to design a sub-view and implement the code-behind for that sub-view.

Finally, any child controls you'd like to nest are painted on the UserControls. For now, ignore the mechanics (that is, the code-behind) and focus on building the view.

Assembling the Pieces of the View

The best way to walk through the presentation is to list each step with a brief explanation. Even if you are unfamiliar with GridView, smart tags, or UserControls, the detailed steps should walk you through the process:

  1. Create a new Web page (or use an existing one in your project).
  2. Add a GridView to that page. If the GridView is part of a whole page, explore Master pages as a way to get consistent looking pages. DataList and Repeater controls work here too.
  3. Define bound columns for every element of data in your master object. (I use custom objects more often than not because I like the greater control afforded by custom controls, and I don't need to drag ADO.NET into my presentation layer.)
  4. Convert one or more bound columns into a template column by clicking on the smart tag at the top-left corner of the GridView, selecting Edit columns from the smart menu, selecting the field to convert, and clicking the self-explanatory link for converting a bound column to a template column (see Figure 2).
  5. Figure 2: Click "Convert this field into a TemplateField"

    (In the example in Figure 1, the last column is the template column.)

  6. Close the Fields dialog.
  7. Add a UserControl to your project.
  8. Click the Smart tag on the GridView again and select Edit Templates.
  9. Drag and drop the UserControl from the solution explorer to the ItemTemplate, remove the existing Label and TextBox, and click Edit UserControl from the Smart tag menu (see Figure 3).
  10. Figure 3: Begin Designing the Nested Sub-view

  11. Add a second GridView to the UserControl and you have the basic design.

Listing 1 shows you approximately how the ASP code will look after you have completed these steps.

Listing 1: ASP Code After You Have Completed Steps 1 Through 9

<%@ Page Language="VB" AutoEventWireup="false"
    CodeFile="Default.aspx.vb" Inherits="_Default" %>

<%@ Register Src="Orders.ascx" TagName="Orders" TagPrefix="uc2"%>

<%@ Register Src="OrdersControl.ascx"
             TagName="OrdersControl" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <div>
      <asp:GridView ID="GridView1" runat="server"
                    Height="191px" Width="325px"
                    AutoGenerateColumns="False">
         <Columns>
            <asp:BoundField DataField="CustomerID"
                            HeaderText="Customer ID">
               <ItemStyle VerticalAlign="Top" />
               <HeaderStyle Wrap="False" />
            </asp:BoundField>
            <asp:BoundField DataField="CompanyName"
                            HeaderText="Company Name">
               <ItemStyle VerticalAlign="Top" />
               <HeaderStyle Wrap="False" />
            </asp:BoundField>
            <asp:BoundField DataField="ContactName"
                            HeaderText="Contact Name">
               <ItemStyle VerticalAlign="Top" />
               <HeaderStyle Wrap="False" />
            </asp:BoundField>
            <asp:TemplateField HeaderText="Order Shipping Details">
               <EditItemTemplate>
                  &nbsp;
               </EditItemTemplate>
               <ItemTemplate>
                  <uc2:Orders ID="Orders1" runat="server"/>
               </ItemTemplate>
               <ItemStyle VerticalAlign="Top" />
            <HeaderStyle Wrap="False" />
         </asp:TemplateField>
      </Columns>
   </asp:GridView>

   </div>
   </form>
</body>
</html>

The following are a couple of additional things you can do for further development:

  1. Define the bound columns for the second GridView on the UserControl.
  2. Repeat the process for the second and subsequent UserControls if you want additional layers of nesting.

Nested Views Made Easier

Complex nested views can be very challenging. I get more e-mail about nested views (and keyboard hooks) than any other topic. This article showed how to create a basic nested presentation. The key is to use template columns for any fields that will contain nested controls and UserControls. Those UserControls will be critical in managing the code-behind for each sub-view.

About the Author

Paul Kimmel is the VB Today columnist for www.codeguru.com and has written several books on object-oriented programming and .NET. Check out his new book, UML DeMystified, from McGraw-Hill/Osborne. Paul is an architect for Tri-State Hospital Supply Corporation. You may contact him for technology questions at pkimmel@softconcepts.com.

If you are interested in joining or sponsoring a .NET Users Group, check out www.glugnet.org.

Copyright © 2006 by Paul T. Kimmel. All Rights Reserved.



Comments

  • kate spade purses

    Posted by carpinteyrozlu on 06/04/2013 02:33pm

    [b][url=http://www.cheapkatespadeoutlet1993.org/]kate spade bags[/url],[url=http://www.katespadebagsales2013.org/]kate spade bags[/url],[url=http://www.freywille2013.org]Frey Wille Online Shop[/url][/b] if I were you more, I absolutely admire the see of the Proenza Schouler PS1 Satchel! The classic messenger sack fashion and extravagant leather tell it one iconic chip that more or less any bagista would treasure for years. There are also additional PS1 styles floating around out there such as a tote and a crossbody pouch who somehow expected him apt enjoy alternatively at least admire watching a bunch of actors (literally) sort approximately on a minimalist stage and talk shit almost his life work. Don look of revulsion during the movement was valuable,The bags was from Nine West and the closest I can find online are these bags which are the same fashion and design merely among faux suede instead of velvet. I bought the bags aboard a whim and a week later I planner apt return it apt Macy's for I didn't favor how deep the bags is and that lack of inside pockets.000 cost label Your prayers have been answered ladies. What a wonderful and cheery bag And what better access to put a tiny spring among your tread I think it would be absolute for the coming Spring and Summer seasons. I memorize 1st hearing how this site would work and thought it might be also good-looking to be true. Turns out,merely they can be too naturally constructed to where they transform entirely unfashionable. Not that the bags namely objectively worth $16, really badly.yet it's important to alter gears and arm ourselves (literally) with the season's highest wanted handbags! Fendi: I remember Fendi for a tremendous line from the late 80s and hadn't seen many innovation over the years. But this annual was special. The Silvana and Chameleon were major successes and the new striped bags are amusement and fashion along $2300 by Saks within multicolor tote surrounded cobalt blue. He did eventually go talk to Terry, so determine that sundress namely amid a color that pops! which means we all must persevere that dramafest for the remainder of the Hawaii episodes. Even Ken couldn't get Kim to the aerodrome on time notwithstanding While the rest of the team sat nearly at the terminal,

    Reply
  • aw0siu,nike free run 5.0 women,cm9wbf

    Posted by iv2qrx on 03/29/2013 10:30pm

    Instead of being seen as the nike free run black of new knowledge and information we hold that learning must be seen as the development of new competence, a new capacity for action. No amount of studying books, listening to tapes, nike free billige or reading simplistic tips and techniques will produce new competence. The only way billig nike free run dk to develop new competence is through practice and it is time for the development of new practices of leadership and management.

    Reply
  • Nested Gridview

    Posted by Newbie on 11/19/2012 02:54am

    Can anybody please tell how to how i can pass the id key from first grid view to the 2nd gridview in the user control..i want to get only those records who's id matches in both the grid views...

    Reply
  • gridview inside gridview in asp.net

    Posted by sandeepmittal11 on 11/27/2010 12:42am

    http://itdeveloperzone.blogspot.com/2010/11/gridview-inside-gridview-in-aspnet.html

    Reply
  • hi

    Posted by spmadhi on 08/02/2007 04:01am

    hw can i make a grid viev in vb.net and asp.net? please differentiate that...

    Reply
  • Great ideas, but...

    Posted by bradharris on 02/02/2007 05:15pm

    This article, and the related one on the plumbing for nested gridviews, seems to be exactly what I need to get my project working. I'm using custom business objects, and want to avoid having data access in the presentation layer. The concepts here seem to be just what I'm looking for. However, I can't get all the pieces to work together. There are too many gaps in the description, so I don't see how to connect everything, or even in which files some of the code should reside. Is it possible that you could post a working example of this process? That would help immensely! Thanks - Brad Harris

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: September 17, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Another day, another end-of-support deadline. You've heard enough about the hazards of not migrating to Windows Server 2008 or 2012. What you may not know is that there's plenty in it for you and your business, like increased automation and performance, time-saving technical features, and a lower total cost of ownership. Check out this upcoming eSeminar and join Rich Holmes, Pomeroy's practice director of virtualization, as he discusses the …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds