Nested GridView in ASP.Net

GridViews are very powerful in .NET. The last GridView article shows a GridView example and how to work with GridViews with ASP.NET controls.


Now, this article shows how to work with multiple GridViews in ASP.NET.

This article was created in India state and their city with a nested GridView example.

This nested grid example uses two GridViews. One GridView for the state data and the second one for the cities.

For the first create two tables, State and City, in your SQL database.

Step 1: Database Side

Create an India State table.

  1. Create table India_State  
  2. (  
  3.    S_id int identity(1,1) primary key,  
  4.    S_code varchar(3),  
  5.    S_name varchar(30)  
  6. )  
And add some data to this table as in the following.

add some data in this tabl

Create City Table
  1. create table City  
  2. (  
  3.    City_id int identity(1,1) primary key,  
  4.    City_code varchar(3),  
  5.    City_name varchar(30),  
  6.    S_id int foreign key references India_state(S_id)  
  7. )  
Also add some records to the city table as in the following.

record

Step 2: Page Desgin side

Now move to Visual Studio and add a new .aspx design page to your project and also provide a suitable name for the nested GridView demo as in the following:
  1. <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true" CodeBehind="NestedGridview.aspx.cs"   
  2. Inherits="Test_WebApplication.BlogWork.NestedGridview" %>  
  3. <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">  
  4. </asp:Content>  
  5.   
  6. <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">  
  7.   
  8.     // write here javascriptcode, css & girdview design code  
  9. </asp:Content>  
Now first add a style sheet for the GridView as in the following:
  1. <div>  
  2.     <style type="text/css">  
  3.         body  
  4.         {  
  5.             font-family: Times New Roman;  
  6.             font-size: 10pt;  
  7.         }  
  8.         .Grid th  
  9.         {  
  10.             background-color: #DF7401;  
  11.             color: White;  
  12.             font-size: 10pt;  
  13.             line-height:200%;  
  14.         }  
  15.         .Grid td  
  16.         {  
  17.             background-color: #F3E2A9;  
  18.             color: black;  
  19.             font-size: 10pt;  
  20.             line-height:200%;  
  21.             text-align:center;  
  22.         }  
  23.         .ChildGrid th  
  24.         {  
  25.             background-color: Maroon;  
  26.             color: White;  
  27.             font-size: 10pt;  
  28.         }  
  29.         .ChildGrid td  
  30.         {  
  31.             background-color: Orange;  
  32.             color: black;  
  33.             font-size: 10pt;  
  34.             text-align:center;  
  35.         }  
  36.     </style>  
  37. </div>  
In this example use a JavaScript function to display a child GridView record and also hide the records in this nested GridView example as in the following:
  1. <div>  
  2.    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  3.     <script type="text/javascript">  
  4.         function StateCity(input) {  
  5.             var displayIcon = "img" + input;  
  6.             if ($("#" + displayIcon).attr("src") == "../image/Detail.jpg") {  
  7.                 $("#" + displayIcon).closest("tr")  
  8.                 .after("<tr><td></td><td colspan = '100%'>" + $("#" + input)  
  9.                 .html() + "</td></tr>");  
  10.                 $("#" + displayIcon).attr("src""../image/hide.jpg");  
  11.             } else {  
  12.                 $("#" + displayIcon).closest("tr").next().remove();  
  13.                 $("#" + displayIcon).attr("src""../image/Detail.jpg");  
  14.             }  
  15.         }  
  16.     </script>  
  17. </div>  
After adding two GridViews to your project Contents page. In this one GridView display the State data and another GridView display the City record. Therefore the State GridView works as the parent grid and the city GridView works as the child grid.

Here in this example first GridState works as the parent grid and inside the second grid GridCity is the child GridView. In this both the parent grid and child grid define DataKeyNames as in the following:
  1. <div>  
  2.    <asp:GridView ID="GridState" runat="server" AutoGenerateColumns="false" DataKeyNames="S_id"  
  3.          CssClass="Grid" onrowdatabound="GridState_RowDataBound" >  
  4.         <Columns>  
  5.         <asp:TemplateField ItemStyle-Width="20px">  
  6.         <ItemTemplate>  
  7.             <a href="JavaScript:StateCity('div<%# Eval("S_id") %>');">  
  8. <img alt="City" id="imgdiv<%# Eval("S_id") %>"   src="../image/Detail.jpg" />  
  9.             </a>  
  10.             <div id="div<%# Eval("S_id") %>" style="display: none;">  
  11. <asp:GridView ID="GridCity" runat="server" AutoGenerateColumns="false" DataKeyNames="S_id"  
  12. CssClass="ChildGrid" >  
  13.     <Columns>  
  14. <asp:BoundField ItemStyle-Width="150px" DataField="City_code" HeaderText="City Code" />  
  15.     <asp:BoundField ItemStyle-Width="200px" DataField="City_name" HeaderText="City Name" />  
  16.                 </Columns>  
  17.                 </asp:GridView>  
  18.             </div>  
  19.         </ItemTemplate>  
  20.         </asp:TemplateField>  
  21.               
  22.             <asp:BoundField ItemStyle-Width="100px" DataField="S_Code" HeaderText="State Code" />  
  23.             <asp:BoundField ItemStyle-Width="150px" DataField="S_Name" HeaderText="State Name" />  
  24.         </Columns>  
  25.     </asp:GridView>  
  26. </div>  
Step 3: Page Code Side

Now go to the page code.

First set the connection string in the web.config file to connect to the database to get the GridView record.
  1. <connectionStrings>  
  2.     <add name="connstr" connectionString="Data Source=RAKESH-PC;Initial Catalog=SqlServerTech;User ID=sa;Password=****" providerName="System.Data.SqlClient"/>  
  3.        <add name="Pratical_testConnectionString" connectionString="Data Source=RAKESH-PC;Initial Catalog=Pratical_test;User ID=sa" providerName="System.Data.SqlClient"/>  
  4. </connectionStrings>  
Now for the first State data fill in the parent GridView with the page load and Chid grid data is obtained in the parent GridView RowDataBound event as in the following code:

Page Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Configuration;  
  8. using System.Data;  
  9. using System.Data.SqlClient;  
  10.   
  11. namespace Test_WebApplication.BlogWork  
  12. {  
  13.     public partial class NestedGridview : System.Web.UI.Page  
  14.     {  
  15.         string conString = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;  
  16.         protected void Page_Load(object sender, EventArgs e)  
  17.         {  
  18.             string sQuery = "SELECT S_id,S_code,S_name from India_state";  
  19.             GridState.DataSource = getData(sQuery);  
  20.             GridState.DataBind();  
  21.               
  22.         }  
  23.         protected void GridState_RowDataBound(object sender, GridViewRowEventArgs e)  
  24.         {  
  25.             if (e.Row.RowType == DataControlRowType.DataRow)  
  26.             {  
  27.                 string S_id = GridState.DataKeys[e.Row.RowIndex].Value.ToString();  
  28.                 string sQuery = "SELECT City_code,City_name,S_id FROM City  WHERE S_id='" + S_id + "'";  
  29.                 GridView SC = (GridView)e.Row.FindControl("GridCity");  
  30.                 SC.DataSource = getData(sQuery);  
  31.                 SC.DataBind();  
  32.             }  
  33.         }  
  34.         private DataTable getData(string sQuery)  
  35.         {  
  36.             SqlDataAdapter sdt = new SqlDataAdapter();  
  37.             DataTable dTable = new DataTable();  
  38.             SqlConnection con = new SqlConnection(conString);  
  39.             con.Open();  
  40.             SqlCommand cmd = new SqlCommand(sQuery, con);  
  41.             sdt.SelectCommand = cmd;  
  42.             sdt.Fill(dTable);  
  43.             con.Close();  
  44.             return dTable;  
  45.         }  
  46.     }  
  47. }  
Step 4: Browser Side

Fill in the State record in the GridView with Page Load.

 
Fill in the City record in the child grid as per selecting the parent grid's State Detail.

Fill City Record

I hope you understand how to work with a nested GridView.


Similar Articles