GridView is an important control which widely used in web development application. GridView is nothing more than a collection of items that indicate what properties from data source are included in the render output along with how the data will be displayed. That is The GridView view mode displays a list of data items by binding data fields to columns and by displaying a column header to identify the field. There are lots of fields which plays an important role to bind data with data source (SQL DataSource or DataBase) some namely as, Bound field, Template field, Image Field etc.

Here I am focusing on how we can use GridView inside GridView i.e nested gridview. Let’s see the brief demonstraton on use of nested gridview.

Step 1: Open Visual Studio and select new project from File menu and select website.

Step 2: After create successful new project drag gridview from toolbox and drop it on web page where you want.

After successfully drag gridview on the page you can perform many tasks such as you can edit format of gridview , edit columns and many more.

GridView inside GridView in ASP.Net (Nested GridView)

Here when you click on the Auto Format then following window will be appear where you have more choice like

GridView inside GridView in ASP.Net (Nested GridView)

Now when you click on edit columns then following window will be appear where you can add different types of fields

GridView inside GridView in ASP.Net (Nested GridView)

Here I am adding three template field.

 Step 3:  Now for performing nested gridview or gridview inside gridview you can write the following   code.

         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
           
            CellPadding="4" EnableModelValidation="True"
            ForeColor="#333333" GridLines="None" onrowcommand="GridView1_RowCommand" onrowcancelingedit="GridView1_RowCancelingEdit"
           
            >
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Department_Id">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("did") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("did") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department_Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("department") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("department") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
               
                <asp:TemplateField HeaderText = "Details">
                     <ItemTemplate>
 
                       <asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%# Container.DataItemIndex%>' />
                       <asp:Button ID ="Cancel" Text="Cancel" runat= "server" CommandName= "Cancel" CommandArgument='<%# Container.DataItemIndex%>' Visible="false" />
                     <%--child gridview with bound fields --%>
                       <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
             CellPadding="4" EnableModelValidation="True"
            ForeColor="#000000" GridLines="Both">
                        <Columns>
                          <asp:BoundField DataField="Emp_Id" HeaderText= "Emp_Id" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Dep_Name" HeaderText= "Dep_Name" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Name" HeaderText= "Name" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Address" HeaderText= "Address" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Department" HeaderText= "Department" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Designation" HeaderText= "Designation" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Technology" HeaderText= "Technology" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                         </Columns>
                         <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                        </asp:GridView>
                    </ItemTemplate>
          
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        </asp:GridView>

The Deisgn of GridView as follows

GridView inside GridView in ASP.Net (Nested GridView)

After the design is complete write the following code in .cs file.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(objectsender, EventArgse)
    {
        if (!IsPostBack)
        {
            ///// bind data with parent gridview when page first time loaded
            SqlConnection con= new SqlConnection(ConnectionString.ConnString());
            con.Open();
            SqlDataAdapter da= new SqlDataAdapter();
            da.SelectCommand= newSqlCommand("select did , Department from tblDepartment", con);
            DataSet ds= newDataSet();
            da.Fill(ds);
            GridView1.DataSource=ds;
            GridView1.DataBind();
           
        }
 
    }
 
    /// <summary>
    /// This event raised when button clicked within GridView
    /// </summary>
 
    protected void GridView1_RowCommand(objectsender, GridViewCommandEventArgse)
    {
        /// takes the command argument row index
        introwindex=Convert.ToInt32(e.CommandArgument.ToString());
        //// find child gridview control
        GridView grv= (GridView)GridView1.Rows[rowindex].FindControl("GridView2");
 
        ////  text for which details display
        Labellbl=  (Label) GridView1.Rows[rowindex].FindControl("Label2");
        GridView1.Rows[rowindex].FindControl("Cancel").Visible= false;
       
        ////
        if (e.CommandName=="Details")
        {
            GridView1.Rows[rowindex].FindControl("Cancel").Visible= true; 
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible= false;   
            SqlConnection con= new SqlConnection(ConnectionString.ConnString());
            con.Open();
            SqlDataAdapter da= new SqlDataAdapter();
            DataSet ds= newDataSet();
            if (lbl.Text=="HR Department")
            {
                da.SelectCommand=new SqlCommand("Select * from tblHR", con);
                da.Fill(ds);
            }
            else if (lbl.Text=="Sales Department")
            {
                da.SelectCommand=new SqlCommand("Select * from tblSales", con);
                da.Fill(ds);
            }
            else
            {
                da.SelectCommand=new SqlCommand("Select * from tblTechnical", con);
                da.Fill(ds);
            }
            ////// bind data with child gridview
            grv.DataSource=ds;
            grv.DataBind();
            grv.Visible=true;
        }
        else
        {
            //// child gridview  display false when cancel button raise event
            grv.Visible=false;
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible= true;
        }
    }
 
    /// <summary>
    /// row cancel event when clicked on cancel button
    /// </summary>
 
    protected void GridView1_RowCancelingEdit(objectsender, GridViewCancelEditEventArgse)
    {
 
    }
}

When you debug this code and click on details button then output will be

GridView inside GridView in ASP.Net (Nested GridView)

If want see all details of column Department_Name then you can see after clicking all details button.

GridView inside GridView in ASP.Net (Nested GridView)

Summary:

Here we are taking two gridview control first is parent gridview and second one is child gridview control. Parent gridview control contain three category HR department, Technical department and sales department, and all the category have some information which are showing in child gridview control when click on Details button.


  1. Assume that I am writing a function as follows


    private void PopulateCheckedValues()
        {
            ArrayList userdetails = (ArrayList)Session["CHECKED_ITEMS"];
            if (userdetails != null && userdetails.Count > 0)
            {
                GridView gv = (GridView)gvCustomers.FindControl("gvOrders"); 
                foreach (GridViewRow gvrow in gv.Rows)
                {
                    int index = (int)gv.DataKeys[gvrow.RowIndex].Value;
                    if (userdetails.Contains(index))
                    {
                        CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkBoxChild");
                        myCheckBox.Checked = true;
                    }
                }
            }
        }

    I would like to get the child grid view in this function can you help me also how can I apply javascript for child grid view

  1. Hi Dorababu M,
    To get the Child GridView in this function, just call this function on GridView RowCommand and write the following code of line;

    GridView 
            grv =
     (GridView)MainGridViewId.Rows[e.CommandArgument.ToString()].FindControl("ChildGridViewId");

    If you want to apply javascript for child gridview, first of all make a javascript function with name CheckBoxFunction() and call it child gridview header template like this....
     <HeaderTemplate>
               <input id="chkBoxAll" type="checkbox" onclick="CheckBoxFunction()" />
      </HeaderTemplate>
    Here, I'm calling this function on checkbox click event. You may call it on other event too depends on your requirment.
    I hope it might be resolve your problem.

  1. Hi Anil,
    You can make your own table as per your requirement, here I've used a dummy table with some text fields which are showing above and simply bind with gridview control. Which type of functionality you're talking about, can you explain your question in more details.

Leave Comment