Click here to Skip to main content
Click here to Skip to main content

Multilevel Nested Master/Detail Data Display Using GridView

, 18 Jul 2006
Rate this:
Please Sign up or sign in to vote.
How GridViews can be used to show data having multilevel master detail relationships.

Sample Image


This article presents how the GridView control can be nested to show master/detail relationships for multilevel hierarchal data. In this article, I have implemented it for three levels, and it can be implemented for n levels quite easily, by maintaining the information about the edit index of the parent GridView controls.

This article provides a simple, easy, and clean solution for displaying data with multilevel master/detail relationships. This article also shows how the GridView can be used effectively by using its template fields, and how controls inside template fields are accessed and bound. More importantly, you will realize the power of GridView's edit mode, and learn how it can be used to do things other than editing; evading from its default usage!!


I happened to work on an HRM system of a company where I had to display details of employees' log events. This was a three level master detail relationship. At the first level, I had to show all the employees of the company (in a ParentGridView). When clicked at any employee, at the second level, I had to show the days in a month when he/she was present (in a ChildGridView), and on the third level, when clicked on a particular day, the corresponding log events of that day (login or log out) had to be displayed (in a GrandChildGridView). I implemented this multilevel master detail relationship by handling the OnRowEditing event of a GridView just to get the new edit index of the parent GridView and save it in the session for the child GridViews.

Using the code

In this particular demo version, I have used Northwind’s Pubs database. The tables Publishers, Titles, and Roysched have a three level master detail hierarchical relationship: each publisher has published multiple titles, and each title has multiple royalty schedules. There is a parent GridView named ParentGridView showing the Publishers table, a child GridView named ChildGridView to display the corresponding records of the Titles table, and a grand child GridView named GrandChildGridView to show the corresponding royalty schedule of a particular title. All parent GridViews need to be templated to show the child one in edit mode. The SelectCommand for the ParentGridView shows that it will have three template fields, pub_id, pub_name, and city, yet there will be a fourth template field that will be used to show the child GridView.

SelectCommand="SELECT [pub_id], pub_name], [city] FROM [publishers]";

I have removed the formatting code and explained the implementation of all three GridViews separately for the sake of clarity. I will show where a child GridView should be nested by writing its name with a star just to increase readability and understanding.

Parent GridView

The parent GridView is templated for all columns selected in the SelectCommand. As you can see, in the code, there is one more template field named ‘View’ which is the only part where the magic lies! In its IetmTemplate, there is a button with the Text, ‘+’, and CommandName, ‘Edit’. This plus sign button, when clicked, lets the GridView to enter edit mode, and fires the OnRowEditing event which is handled. What is to be shown in the edit mode is implemented in the EditItemTemplate. As shown in the code, it has a button with CommandName 'Cancel' and Text ‘-’ (to collapse the GridView by just running the Cancel command, which resets the edit index to -1 and the ParentGridView comes out of editing mode; obviously, the ChildGridView shown in edit mode will no longer be visible, which gives the notion of collapsibility). Next to the Cancel ‘-' button is a ChildGridView.

<asp:GridView ID="ParentGridView" runat="server"
  OnRowEditing= "ParentGridView_OnRowEditing" 
     <asp:TemplateField HeaderText="PublisherID">
           <asp:Label id="pubid_lbl" Runat="Server" 
           Text='<%# Eval("pub_id") %>'/>
     <asp:TemplateField HeaderText="Name">
           <asp:Label id="name_lbl" Runat="Server" 
           Text='<%# Eval("pub_name") %>'/>
    <asp:TemplateField HeaderText="City">
            <asp:Label id="city_lbl" Runat="Server" 
            Text='<%# Eval("city") %>'/>
    <asp:TemplateField HeaderText="View">
            <asp:Button ID="ViewChild_Button" 
                  runat="server" Text="+"   CommandName="Edit" />
            <asp:Button ID="CancelChild_Button" 
                  runat="server" Text="-" CommandName="Cancel" />
            *ChildGridView…will come here

The event handling code for OnRowEditing is quite self-explanatory, yet it's is important to know that the OnRowEditing event does not have any code for editing. Instead, it sets the the ParentGridView’s edit index to that of the current row and binds it. It saves the index and pub_id in the session, because later, we’ll need both of them: pub_id to get the corresponding tuples of Titles against it, and ParentGridViewIndex is needed to find the row containing the ChildGridView whose row has been selected.

protected void ParentGridView_OnRowEditing(object sender, 
                              GridViewEditEventArgs e)
    int parent_index = e.NewEditIndex;
    //to set the edit index of the Parent 
    //grid with that of the current row
    ParentGridView.EditIndex = parent_index;
    //find the pubid_lbl containing pub_id in that 
    //particular row by using findcontrol method
    GridViewRow row = ParentGridView.Rows[parent_index];
    Label pub_id_lbl = (Label)row.FindControl("pubid_lbl");
    //save pub_id and edit_index in session for childgridview's use
    Session["PubID"] = Convert.ToInt32(pub_id_lbl.Text);
    Session["ParentGridViewIndex"] = parent_index;

Child GridView

Let's take a look at the SelectCommand of the DataSource for the ChildGridView. Its WHERE clause needs pub_id, which we have already stored in Session[“Pub_ID”].

<SelectCommand="SELECT [title_id],[title], [type],[price] 
                FROM [titles] WHERE ([pub_id] = ?) ORDER BY [price]">
     <asp:SessionParameter Name="PubID" SessionField="PubID" Type="Int32" />

The GrandChildView is templated in the same way as ParentGridView. It also has a template field named ‘View’ to show its own child grid (GrandChildGridView) with the same buttons, and the same commands on the same positions. It also implements its OnRowEditing, which is a little different than that of its parent. Here, the child grid view is not directly accessible as it is nested in the parent one. To set its edit index with new edit index, first we need to find it from the particular row of ParentGridView. The row of ParentGridView containing the ChildGridView is found using ParentGridViewIndex from the session variable.

int parent_index =(int)Session["ParentGridViewIndex"];
GridViewRow parent_row = ParentGridView.Rows[parent_index];

We now have the row of ParentGirdView containing the ChildGridView. Now, we simply use the FindControl method to find the ChildGridView.

GridView ChildGridiView = 

The title_id of the selected title is stored in the session, and that will be used by its own child gird, i.e., GrandChildGridView. The complete code for the event is as follows:

protected void ChildGridView_OnRowEditing(object sender, 
                             GridViewEditEventArgs e)
    //set the edit index of the child 
    //gridview with that of the current row
    int parent_index =(int)Session["ParentGridViewIndex"];
    GridViewRow parent_row = ParentGridView.Rows[parent_index];
    GridView ChildGridiView = 

    int child_index = e.NewEditIndex;
    ChildGridiView.EditIndex = child_index;
    //find the titleid_lbl in that particular 
    //row by using findcontrol method
    GridViewRow child_row = ChildGridiView.Rows[child_index];
    Label titleid_lbl = (Label)child_row.FindControl("titleid_lbl");
    // save the title_id in session for grandchildgridview's use
    Session["TitleID"] = titleid_lbl.Text;

Here is the aspx source of ChildGridView. The template field named View shows the GrandChildGridView with a star that will be substituted at this place.

<asp:GridView ID="ChildGridView" 
       runat="server" AllowPaging="true" PageSize="4"
       OnRowEditing= "ChildGridView_OnRowEditing" >
          <asp:TemplateField HeaderText="TitleID">
                 <asp:Label id="titleid_lbl" Runat="Server" 
                 Text='<%# Eval("title_id") %>'/>
             <asp:TemplateField HeaderText="Title">
                <asp:Label id="title_lbl" Runat="Server" 
             Text='<%# Eval("title") %>'/>
        <asp:TemplateField HeaderText="Type">
           <asp:Label id="type_lbl" Runat="Server" 
           Text='<%# Eval("type") %>'/>
       <asp:TemplateField HeaderText="Price">
            <asp:Label id="price_lbl" Runat="Server" 
            Text='<%# Eval("price") %>'/>
       <asp:TemplateField HeaderText="View">
           <asp:Button ID="ViewGrandChild_Button" 
                 runat="server" Text="+"   CommandName="Edit"/>
           <asp:Button ID="CancelGrandChild_Button" 
                 runat="server" Text="-" CommandName="Cancel" />
           *GrandChildGridView will come here

Grand Child GridView

The WHERE clause of GrandChildDataSource’s SelectCommand needs the value of title_id from its immediate parent table that was stored in the session when the particular title was selected. It is now being used to show all the rows of the roysched table against it in the GrandChildGridView.

<SelectCommand="select [lorange],[hirange],roysched.royalty 
                from [roysched], [titles] where 
                and (roysched.title_id=?)">
    <asp:SessionParameter Name="title_id" 
         SessionField="TitleID" Type="String"/>

There is no need to use GrandChildGridView with template fields as we don't need any further child relationship with it. Otherwise, we'll have to implement it using template fields.

<asp:GridView ID="GrandChildGridView" runat="server" 
      AllowPaging="true" PageSize="4" 

Points of Interest

It is important to know that I have used the GridView's Edit mode for displaying the child GridView. No editing is done in the Edit mode, yet simultaneously, it can be done if desired. The OnRowEditing event does not contain any code for editing, rather it does what is needed; the edit index and the primary key value stored in the session will be used in the OnRowEditing event of the child GridViews for searching the particular row of the parent GridView and finding the child GridView from it, and later will be used in the SelectCommand of the child GridView to get all the child rows against that particular parent ID. The Cancel command already does what we want; it cancels the editing, and the parent GridView comes out of the Edit mode hiding its child GridView.

If any parent GridView is collapsed in the hierarchy, its entire children will automatically collapse.

More importantly, it can be implemented for any number of levels by simply keeping the track of primary keys and edit indexes of all parent GridViews of a child GridView. Every child GridView knows its own edit index whereas it needs to know the edit index of all its parent GridViews, which can be provided by storing the edit index of each parent GridView in the session and using them when needed to find a particular row containing the child GridView. Lastly, always place a SqlDataSource control besides a GridView otherwise a child GridView will no longer be able to access it.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Mahr G Mohyuddin
Software Developer (Senior)
Pakistan Pakistan
Mohyuddin is a Senior Software Engineer with BS Honors degree in Computer Science from Punjab University College of Information Technology (PUCIT),Lahore Pakistan. His interest and expertise are in Microsoft technologies specially SharePoint 2010, InfoPath 2010 , Workflow , MS Dynamics CRM, ASP.NET 2.0/3.0, ASP.NET MVC, C#,ADO.NET, LINQ , SQl Server ,Ajax, JQuery. Currently he is working at VeriPark Gulf, Dubai, UAE. He can be reached at gmohyd at g

Comments and Discussions

GeneralMy vote of 4 Pinmemberthelizard13-Aug-12 11:17 
QuestionDATABASE Pinmembergerardgillman17-Nov-11 10:30 
GeneralMultilevel Nested Master/Detail Pinmemberh_waystar4-May-11 9:23 
GeneralMy vote of 5 PinmemberMember 41788502-Mar-11 22:23 
GeneralMy vote of 5 Pinmembergopikishna14-Jan-11 15:19 
GeneralMy vote of 5 Pinmemberboster_s16-Dec-10 10:08 
GeneralMy vote of 5 [modified] PinmemberEswa9-Nov-10 0:36 
GeneralOnRowEditing event doesn't fire. PinmemberRoger Withnell6-Jul-10 6:24 
GeneralRe: OnRowEditing event doesn't fire. PinmemberMiguelAJH28-Jul-10 8:42 
I have the same problem!!!
El diablo no sabe ni por diablo ni por viejo sino porque lee los manuales

GeneralExcellent Guide PinmemberLeeOsenton5-May-10 4:32 
GeneralUrgent need:Onrowediting of Childgrid inside parent grid Pinmemberanushh19-Apr-10 21:28 
GeneralThanks for writing this! PinmemberDavidLieu25-Feb-10 11:28 
QuestionMulti level hierarchy PinmemberprasadSn200323-Feb-10 21:44 
GeneralHi PinmemberRavenet2-Nov-09 5:18 
QuestionSorting Feature Pinmembersunny3522-Jul-09 4:55 
GeneralMultilevel Nested Master/Detail Data Display Using GridView Pinmemberyrbyogi20-Apr-09 2:26 
GeneralProblem on pageindexchanging Pinmemberudayakumarziv17-Nov-08 17:53 
Questionhow to calculate Pinmemberudayakumarziv16-Nov-08 18:29 
General[Message Removed] Pinmembernompel6-Oct-08 9:13 
GeneralGood Article PinmemberAsween5-Sep-08 9:50 
GeneralRe: Good Article PinmemberMahr G. Mohyuddin7-Sep-08 18:50 
GeneralNeed help.. in my scenario.. Pinmemberprsm22-May-08 5:07 
Questionby Ankam - Gridview pageindexchanging is not working [modified] Pinmembericanmakeiteasy17-Jan-08 1:14 
GeneralRe: by Ankam - Gridview pageindexchanging is not working PinmemberMahr G. Mohyuddin11-Feb-08 18:57 
Questionlogin failed for user ('null') Pinmembernambidasan30-Dec-07 23:19 
QuestionHow to use custom queries. PinmemberMember 438315521-Dec-07 10:01 
GeneralThis is a great article and I am trying to test it on a SQL Db but keep getting syntax error near ?. I would appreciate any help on this, THANK YOU Pinmemberramy12-Dec-07 15:18 
GeneralRe: This is a great article and I am trying to test it on a SQL Db but keep getting syntax error near ?. I would appreciate any help on this, THANK YOU PinmemberMember 43835658-Dec-08 9:24 
GeneralExporting To Excel Pinmemberkeng150921-Oct-07 22:51 
Questionhow to update data using store procedure Pinmemberbiswa471-Aug-07 0:55 
Questionhow to display the control name Pinmemberbiswa471-Aug-07 0:54 
AnswerRe: how to display the control name PinmemberG. Mohyuddin1-Aug-07 4:08 
GeneralCheck this error Pinmembersamermf31-Jul-07 5:21 
GeneralAnother way Pinmemberarjun18127-Jul-07 9:05 
Generaldisabled the control in gridview Pinmemberbarbod_blue15-Jul-07 3:06 
GeneralDynamic Template with GridView PinmemberAlpesh Dhanesha22-Jun-07 1:51 
Generalproblem with Mozila PinmemberSujit Gupta28-Apr-07 4:23 
GeneralRe: problem with Mozila PinmemberG. Mohyuddin29-Apr-07 19:17 
QuestionDetail grid in next row, below the Master row PinmemberSiddiq-ur-Rahman Khurram7-Mar-07 18:59 
AnswerRe: Detail grid in next row, below the Master row PinmemberG. Mohyuddin7-Mar-07 21:57 
AnswerRe: Detail grid in next row, below the Master row Pinmemberarajamani20-Feb-09 8:46 
QuestionCan you please provide the same solution for winforms? PinmemberO.S.Chakravarthi23-Feb-07 3:13 
AnswerRe: Can you please provide the same solution for winforms? PinmemberG. Mohyuddin23-Feb-07 22:26 
GeneralParentGridView.DataBind() Fails Pinmembervbgrunt21-Feb-07 9:16 
GeneralRe: ParentGridView.DataBind() Fails PinmemberG. Mohyuddin21-Feb-07 18:34 
GeneralNested GridView with Dropdown Effect Pinmemberetbramble7-Feb-07 5:28 
GeneralRe: Nested GridView with Dropdown Effect PinmemberG. Mohyuddin9-Feb-07 2:32 
Generalneed Help in master/Detail grid Pinmembermahesh kukkadapu19-Jan-07 8:21 
GeneralRe: need Help in master/Detail grid PinmemberG. Mohyuddin21-Jan-07 18:19 
GeneralRe: need Help in master/Detail grid Pinmembermahesh kukkadapu23-Jan-07 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 18 Jul 2006
Article Copyright 2006 by Mahr G Mohyuddin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid