Create Nested Gridview with Expand and Collapse features in ASP.Net

In this blog, I am going to show how we could create a nested gridview i.e gridview inside another gridview. The feature of this nested group is that the sub-grid will be hidden by default and when user clicks on "+" sign provided in Main gridview the subgrid will be shown to the user and "+" sign gets converted to "-" sign and again if user click "-" sign the subgrid gets hidden. The motive behind this is to show the detailed specification of particular record on click of button instead showing all records in a single grid.

Additionally a small javascript has been used inside this code for attractive warning message, you may ignore that portion.


First of all, add the below code inside the .aspx code window::

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="NestedGridview.aspx.cs" Inherits="NestedGridview" %>

<!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></title>
    <style type="text/css">
        p {
            background: #fff6cc url('warning.png') 2px 50% no-repeat;
            border-radius: 6px;
            border: 1px solid #ffd100;
            color: #000;
            padding: 10px 10px 10px 38px;
            width: 76%;
        }
    </style>
    <script language="javascript" type="text/javascript">
        function divexpandcollapse(divname) {
            var div = document.getElementById(divname);
            var img = document.getElementById('img' + divname);
            if (div.style.display == "none") {
                div.style.display = "inline";
                img.src = "images/collapse.jpg";
            } else {
                div.style.display = "none";
                img.src = "images/expand.jpg";
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            // A small code for attractive warning message //
            <p><strong>Warning!</strong> Its just for demonstration. Sub-gidview is shwoing on click of + and hiding on click of - sign. Here "UserId" is the link b/w theses two grids. All values are hardcoded here and just for demostration, you may do the similar functinality with use of database. Motive behind this is to show the detailed specification of particular record on click of button instead showing all records in a single grid</p>
            <br />
            <asp:GridView ID="gvParentGrid" EmptyDataText="Data not available" runat="server" DataKeyNames="UserId" Width="80%"
                AutoGenerateColumns="false" OnRowDataBound="gvUserInfo_RowDataBound">

                <HeaderStyle BackColor="#FFF6CC" Font-Bold="true" ForeColor="black" />
                <Columns>
                    <asp:TemplateField ItemStyle-Width="20px">
                        <ItemTemplate>
                            <a style="border-color: black" href="JavaScript:divexpandcollapse('div<%# Eval("UserId") %>');">
                                <img id="imgdiv<%# Eval("UserId") %>" width="12px" dir="rtl" src="images/expand.jpg" />
                            </a>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="UserId" HeaderStyle-ForeColor="Black" HeaderText="UserId" HeaderStyle-HorizontalAlign="Left" />
                    <asp:BoundField DataField="Name" HeaderStyle-ForeColor="Black" HeaderText="Name" HeaderStyle-HorizontalAlign="Left" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <tr>
                                <td colspan="100%">
                                    <div id="div<%# Eval("UserId") %>" style="display: none; position: relative; overflow: auto">
                                        <asp:GridView ID="gvChildGrid" EmptyDataText="Data Unavailable" runat="server" AutoGenerateColumns="false" Width="100%">

                                            <AlternatingRowStyle BackColor="LightGray" />
                                            <HeaderStyle BackColor="#FFF6CC" Font-Bold="true" ForeColor="black" />
                                            <Columns>
                                                <asp:BoundField DataField="Designation" HeaderStyle-ForeColor="Black" HeaderText="Designation" HeaderStyle-HorizontalAlign="Left" />
                                                <asp:BoundField DataField="Department" HeaderStyle-ForeColor="Black" HeaderText="Department" HeaderStyle-HorizontalAlign="Left" />
                                            </Columns>
                                        </asp:GridView>
                                    </div>
                                </td>
                            </tr>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
    </form>
</body>
</html>


Now, add following code inside the .cs code window. Here all values are hardcoded, you may channge code while using database accordingly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;

public partial class NestedGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
 protected void BindGrid()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("Name", typeof(string));
     

        DataRow dr = dt.NewRow();
        dr["UserId"] = 1;
        dr["Name"] = "Aayush";
     
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 2;
        dr["Name"] = "Anish";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 3;
        dr["Name"] = "Manish";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["UserId"] = 4;
        dr["Name"] = "Ravish";
        dt.Rows.Add(dr);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                {
                    dt.Rows[i][j] = "Data Not Available";
                }
            }
        }
        gvParentGrid.DataSource = dt;
        gvParentGrid.DataBind();
    }
 protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         DataTable dt = new DataTable();
         dt.Columns.Add("Designation", typeof(string));
         dt.Columns.Add("Department", typeof(string));

         DataRow dr = dt.NewRow();
         dr["Designation"] = "Associate Technical Consultant";
         dr["Department"] = null;
         dt.Rows.Add(dr);

         dr = dt.NewRow();
         dr["Designation"] = "Technical Consultant";
         dr["Department"] = null;
         dt.Rows.Add(dr);

         dr = dt.NewRow();
         dr["Designation"] = null;
         dr["Department"] = "Navision";
         dt.Rows.Add(dr);

         dr = dt.NewRow();
         dr["Designation"] = "Tech Lead";
         dr["Department"] = "CRM";
         dt.Rows.Add(dr);

         GridView gv = (GridView)e.Row.FindControl("gvChildGrid");
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             for (int j = 0; j < dt.Columns.Count; j++)
             {
                 if (string.IsNullOrEmpty(dt.Rows[i][j].ToString()))
                 {
                     dt.Rows[i][j] = "Data Not Available";
                 }
             }
         }
         gv.DataSource = dt;
         gv.DataBind();
     }
 }

}

Output::


Comments

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image