Skip to main content

Nested GridView Example In Asp.Net With Expand Collapse


This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality.
I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons.

Nested GridView Example In Asp.Net With Expand Collapse

Customers and Orders Table of Northwind Database are used to populate nested GridViews.

Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags

Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview.

Place another grid in last templateField column.

Markup of page after adding both templatefields will like as shown below.



HTML SOURCE
   1:  <asp:GridView ID="gvMaster" runat="server" 
   2:                AllowPaging="True" 
   3:                AutoGenerateColumns="False" 
   4:                DataKeyNames="CustomerID" 
   5:                DataSourceID="SqlDataSource1" 
   6:                onrowdatabound="gvMaster_RowDataBound">
   7:  <Columns>
   8:  <asp:TemplateField>
   9:      <ItemTemplate>
  10:      <a href="javascript:collapseExpand('customerID-
  11:               <%# Eval("CustomerID") %>');">
  12:      <img id="imagecustomerID-<%# Eval("CustomerID") %>" 
  13:           alt="Click to show/hide orders" 
  14:           border="0" src="plus.png" /></a>
  15:      </ItemTemplate>
  16:  </asp:TemplateField>
  17:  <asp:BoundField DataField="CustomerID" 
  18:                  HeaderText="CustomerID"/>
  19:  <asp:BoundField DataField="CompanyName" 
  20:                  HeaderText="CompanyName"/>
  21:   
  22:  <asp:TemplateField>
  23:  <ItemTemplate>
  24:  <tr><td colspan="100%">
  25:  <div id="customerID-<%# Eval("CustomerID") %>" 
  26:       style="display:none;
  27:       position:relative;left:25px;">
  28:       
  29:  <asp:GridView ID="nestedGridView" runat="server" 
  30:                AutoGenerateColumns="False" 
  31:                DataKeyNames="OrderID">
  32:  <Columns>
  33:  <asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
  34:  <asp:BoundField DataField="OrderDate" HeaderText="OrderDate"/>
  35:  <asp:BoundField DataField="Freight" HeaderText="Freight"/>
  36:  </Columns>
  37:  </asp:GridView>
  38:  </div>
  39:  </td></tr>
  40:  </ItemTemplate>
  41:  </asp:TemplateField>
  42:  </Columns>
  43:  </asp:GridView>
  44:   
  45:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  46:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
  47:  SelectCommand="SELECT [CustomerID], [CompanyName] 
  48:                 FROM [Customers]">
  49:  </asp:SqlDataSource>

Add following JavaScript in head section of page.
01<script type="text/javascript">
02function collapseExpand(obj)
03{
04  var gvObject = document.getElementById(obj);
05  var imageID = document.getElementById('image' + obj);
06 
07  if (gvObject.style.display == "none")
08      {
09         gvObject.style.display = "inline";
10         imageID.src = "minus.png";
11      }
12  else
13     {
14         gvObject.style.display = "none";
15         imageID.src = "plus.png";
16     }
17}
18</script>

Write following code in RowDataBound Event of parent Grid to populate nested gridview.

C#
01protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
02    {
03        if (e.Row.RowType == DataControlRowType.DataRow)
04        {
05            string customerID = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CustomerID"));
06            GridView gvChild = (GridView)e.Row.FindControl("nestedGridView");
07            SqlDataSource gvChildSource = new SqlDataSource();
08            gvChildSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
09            gvChildSource.SelectCommand = "SELECT [OrderID], [OrderDate],[Freight] FROM [Orders] WHERE [CustomerID] = '" + customerID + "'";
10            gvChild.DataSource = gvChildSource;
11            gvChild.DataBind();
12        }
13    }

VB.NET
01Protected Sub gvMaster_RowDataBound(sender As Object, e As GridViewRowEventArgs)
02 If e.Row.RowType = DataControlRowType.DataRow Then
03  Dim customerID As String = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CustomerID"))
04  Dim gvChild As GridView = DirectCast(e.Row.FindControl("nestedGridView"), GridView)
05  Dim gvChildSource As New SqlDataSource()
06  gvChildSource.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
07  gvChildSource.SelectCommand = "SELECT [OrderID], [OrderDate],[Freight] FROM [Orders] WHERE [CustomerID] = '" + customerID + "'"
08  gvChild.DataSource = gvChildSource
09  gvChild.DataBind()
10 End If
11End Sub

Build and run the application to test GridView Inside Grid.

Download Sample Code

Comments

Popular posts from this blog

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...