Click here to Skip to main content
15,391,989 members
Articles / Web Development / HTML
Posted 16 Aug 2007


253 bookmarked

Editable Nested GridView (All-in-One)

Rate me:
Please Sign up or sign in to vote.
4.86/5 (116 votes)
16 Aug 2007CPOL5 min read
How to create an all-in-one editable nested GridView in ASP.NET using C#.

Screenshot - EditNestedGridView.jpg


This article explains how to make an ASP.NET editable nested GridView. Here I am going to explain how to provide all the features of Edit/Add/Delete/Update/Page/Sort of a GridView, and not only one GridView, but I am going to explain how to extend these features to even nested grids (GridView inside GridView). I have provided the fully functional source code, which is self-explanatory.


My previous article explains about the features of nested editable DataGrids. This article provides all those features in a GridView (Visual Studio 2005, .NET 2.0). With the combination of GridView and DataSource controls, it's very easy to create an editable GridView.

Using the Code

This is a web application with a virtual directory named EditNestedGridView. You may create the same virtual directory to run this application with Visual Studio .NET 2005, or create any other virtual directory and map the path to this directory to access it from the browser. As I have used Access 2003 as my database, you need to have Microsoft Access installed on your machine. I have used the NorthWind database with some modifications. I have also included this in the code bundle under the App_Data folder. I have used C# for the code-behind files. In Visual Studio 2005, File --> Open --> Web Site, and navigate to the folder EditNestedGridView.

Step-by-Step Procedure

The code attached is self-explanatory, but I will try to explain it as much as possible.

  1. Since here I am going to use the DataSource control, let's first create an AccessDataSource control as below:
  2. ASP.NET
    <asp:AccessDataSource ID="AccessDataSource1" runat="server" 
        SelectCommand="SELECT [Customers].[CustomerID], 
        [Customers].[ContactTitle],[Customers].[Address] FROM [Customers] 
        ORDER BY [Customers].[CustomerID]"></asp:AccessDataSource>

    The main advantage of the DataSource control is that it simplifies the amount of custom code that needs to be written to retrieve and bind data, and even to sort, page through, or edit data.

  3. Now, let's create a simple GridView control and attach the previously created DataSource control as shown below:
  4. ASP.NET
    <asp:GridView ID="GridView1" AllowPaging="True" BackColor="#f1f1f1" 
                AutoGenerateColumns=false DataSourceID="AccessDataSource1" 
                style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 32px" 
                ShowFooter=true Font-Size=Small
                Font-Names="Verdana" runat="server" GridLines=None BorderStyle=Outset>

    GridView is very similar to DataGrid and it has all those column features of DataGrid like TemplateColumn, BoundColumn to populate data as columns. EditItemTemplate and FooterTemplate can be used for editing and adding purposes. The following code shows the columns of the parent grid:

    <asp:TemplateField HeaderText="Customer ID" SortExpression="CustomerID">
            <asp:Label ID="lblCustomerID" Text='<%# Eval("CustomerID") %>' 
            <asp:Label ID="lblCustomerID" Text='<%# Eval("CustomerID") %>' 
            <asp:TextBox ID="txtCustomerID" Text='' runat="server"></asp:TextBox>
    <asp:TemplateField HeaderText="Company Name" SortExpression="CompanyName">
        <ItemTemplate><%# Eval("CompanyName") %></ItemTemplate>
            <asp:TextBox ID="txtCompanyName" Text='<%# Eval("CompanyName") %>' 
            <asp:TextBox ID="txtCompanyName" Text='' runat="server"></asp:TextBox>
    <asp:CommandField HeaderText="Edit" ShowEditButton="True" />
    <asp:TemplateField HeaderText="Delete">
            <asp:LinkButton ID="linkDeleteCust" CommandName="Delete" 
            <asp:LinkButton ID="linkAddCust" CommandName="AddCustomer" 

    Now that we have all the columns in place, we need the event handlers to take care of the Add/Edit/Delete actions. Handling these events is very straightforward compared to that for the DataGrid. The DataSource control takes care of the paging and sorting actions. Here is the final parent GridView control with all these events.

    <asp:GridView ID="GridView1" AllowPaging="True" BackColor="#f1f1f1" 
                AutoGenerateColumns=false DataSourceID="AccessDataSource1" 
                style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 32px" 
                ShowFooter=true Font-Size=Small
                Font-Names="Verdana" runat="server" GridLines=None 
                OnRowCommand = "GridView1_RowCommand" 
                OnRowUpdating = "GridView1_RowUpdating" BorderStyle=Outset
                OnRowDeleting = "GridView1_RowDeleting" 
                OnRowDeleted = "GridView1_RowDeleted"
                OnRowUpdated = "GridView1_RowUpdated" AllowSorting=true>

    With all the above options, the GridView looks like:

    Screenshot - EditNestedGridView1.jpg

  5. Until now, we have created a parent GridView. Now we are going to extend these features in a child GridView as well.
  6. Before adding another GridView, we must understand how GridView emits its content as HTML tags. For an Internet Explorer browser, GridView is like a regular Table with TR and TD tags. So, if we can manipulate the parent GridView to forcibly close a row and emit a child GridView as another row, we are done with it.

    What is displayed is some HTML table cell and row tags that effectively intercept the current output that will be generated by the GridView with our own special implementation. Namely, we are telling the table (when it's drawn) to close the current cell, the current row, and now add a new row with one blank column (for spacing) and another column (spanning all columns) that we'll use to display a second GridView. Here is the piece of code which explains this:

            <td colspan="100%">
            <div id="div<%# Eval("CustomerID") %>" 
                style="display:none;position:relative;left:15px;OVERFLOW: auto;WIDTH:97%" >

    Here, I have created a division id="div Eval("CustomerID") with an ID of Customer (parent row) which holds the child GridView so that we can dynamically hide and expand it by using the DIV ID. Also, we need a column in the main GridView which holds the image to expand and collapse the child GridView as below:

            <a href="javascript:expandcollapse('div<%# Eval("CustomerID") %>', 'one');">

    Here, the JavaScript function expandcollapse will take care of the expand and collapse action.

  7. In order to bind the child GridView, we can't use the static DataSource control as we have used for the parent GridView. We will have to dynamically prepare the query based on the customer ID of the corresponding parent row, and that we can do it in the RowDataBound event of the parent grid as below:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        GridViewRow row = e.Row;
        string strSort = string.Empty;
        // Make sure we aren't in header/footer rows
        if (row.DataItem == null)
        //Find Child GridView control
        GridView gv = new GridView();
        gv = (GridView)row.FindControl("GridView2");
        //Prepare the query for Child GridView by passing 
        //the Customer ID of the parent row
        gv.DataSource = 

    Here, the ChildDataSource function forms the query using the passed customer ID and returns the AccessDataSource.

  8. Now, we have data in the child grid as well, with dynamic expand and collapse. Let's add the effects one by one as we did for the parent grid. However, before going further, there is a little tricky part involved. In the case of the parent grid, there is only a unique ID (GridView1), and in the case of the child, there will be several unique IDs that get generated at run time. If we can identify the one which we need, that will solve this problem.

    Paging and sorting were taken care of by the DataSource control in the case of the parent grid. For the child grid, we have to take care of it manually using the corresponding events PageIndexChanging and Sorting. A sample code of the paging event looks like:

    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;
        gvNewPageIndex = e.NewPageIndex;

    Here, we have identified the run time unique ID of the child grid which needs paging along with the new page number. We are going to use these variable values in the RowDataBound event of the parent grid, as below:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        //Find Child GridView control
        GridView gv = new GridView();
        gv = (GridView)row.FindControl("GridView2");
        //Check if any additional conditions (Paging, Sorting, Editing, etc) 
        //to be applied on child GridView
        if (gv.UniqueID == gvUniqueID)
            gv.PageIndex = gvNewPageIndex;
            gv.EditIndex = gvEditIndex;
            //Check if Sorting used
            if (gvSortExpr != string.Empty)
                strSort = " ORDER BY " + string.Format("{0} {1}", gvSortExpr, gvSortDir);
            //Expand the Child grid
            ClientScript.RegisterStartupScript(GetType(), "Expand", 
                "<script language="javascript"></script>");

The remaining actions (Sorting/Edit/Update/Delete) can also be handled similarly to paging. Refer to the source code attached above.


The GridView has more features compared to the DataGrid, which will make it easier to code, and also, we can include HTML tags in between for more flexibility.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Veera V Satya N Kanithi
United States United States
No Biography provided

Comments and Discussions

Questionacces adapt database sql Pin
Member 1481486113-May-20 0:44
MemberMember 1481486113-May-20 0:44 
Questionrequest to update code to bind empty nested gridview (gridview with no records) on page load Pin
subanl8-Jan-19 22:29
Membersubanl8-Jan-19 22:29 
AnswerRe: request to update code to bind empty nested gridview (gridview with no records) on page load Pin
MeikR15-Feb-19 0:59
MemberMeikR15-Feb-19 0:59 
QuestionCollapse open gridview row when selecting another row Pin
Member 324697031-Oct-17 0:05
MemberMember 324697031-Oct-17 0:05 
AnswerRe: Collapse open gridview row when selecting another row Pin
MeikR15-Feb-19 1:00
MemberMeikR15-Feb-19 1:00 
Questionhave error Pin
Member 1168600516-Oct-15 18:23
MemberMember 1168600516-Oct-15 18:23 
Questionsimilar functionality on MVC4 Pin
Benion Zeray24-Sep-15 21:44
MemberBenion Zeray24-Sep-15 21:44 
QuestionThank you for code. But a start question : Pin
Member 1190425220-Sep-15 22:53
MemberMember 1190425220-Sep-15 22:53 
QuestionClarification for the solution you provided Pin
Santhosh Chitloor26-Feb-15 20:58
professionalSanthosh Chitloor26-Feb-15 20:58 
AnswerRe: Clarification for the solution you provided Pin
Member 1193827828-Aug-15 10:40
MemberMember 1193827828-Aug-15 10:40 
GeneralThanks For Your Post Pin
hari4sharma13-Aug-14 22:20
Memberhari4sharma13-Aug-14 22:20 
QuestionFailed to load ViewState - Got the error when incorporated this sample application (Editable Nested GridView (All-in-One) ) to my project Pin
Member 43531849-Jun-14 0:31
MemberMember 43531849-Jun-14 0:31 
QuestionChild GridView Also Contains GridView Pin
santos6715-Dec-13 22:31
Membersantos6715-Dec-13 22:31 
AnswerRe: Child GridView Also Contains GridView Pin
smita suryavanshi5-Jul-22 18:44
Membersmita suryavanshi5-Jul-22 18:44 
QuestionSetting the column sizes Pin
Member 1001832414-May-13 9:01
MemberMember 1001832414-May-13 9:01 
Questioneditable nested grid ..problem in nested grid Pin
Member 92501388-Apr-13 1:59
MemberMember 92501388-Apr-13 1:59 
GeneralMy vote of 5 Pin
raj ch15-Mar-13 22:29
Memberraj ch15-Mar-13 22:29 
QuestionHow then can you add a search button? Pin
Sithelo Ngwenya8-Mar-13 2:04
MemberSithelo Ngwenya8-Mar-13 2:04 
GeneralExcellent work Pin
Sithelo Ngwenya8-Mar-13 1:34
MemberSithelo Ngwenya8-Mar-13 1:34 
QuestionBinds to LAST item for GridView2...Help Please...almost there! Pin
dburns234-Dec-12 15:53
Memberdburns234-Dec-12 15:53 
Member 964389230-Nov-12 0:02
MemberMember 964389230-Nov-12 0:02 code Pin
Member 430984518-Nov-12 2:07
MemberMember 430984518-Nov-12 2:07 
GeneralMy vote of 5 Pin
batz099-Nov-12 4:13
Memberbatz099-Nov-12 4:13 
GeneralMy vote of 5 Pin
S Devrajani1-Oct-12 10:52
MemberS Devrajani1-Oct-12 10:52 
GeneralMy vote of 5 Pin
zeego24-Sep-12 0:36
Memberzeego24-Sep-12 0:36 

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

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