Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Gridview inside gridview in asp.net - nested gridview example

May 30, 2012
Introduction

In this article I will explain how to implement gridview with in a gridview example or nested gridview with expand/collapse options in asp.net. 

Description:

In previous posts I explained asp.net gridview examples and
bind data to textbox control in gridview ,Bind data to dropdownlist  in gridview in asp.net. Now I will explain how to implement gridview within gridview or nested gridview example in asp.net.

To implement this concept first design tables (Country and State) in your database as explained in this post populate dropdown based on another dropdown in asp.net. After completion of table design write following code in your aspx page like this 

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Gridview within Gridivew - Nested gridview example in asp.net </title>
<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 = "minus.gif";
} else {
div.style.display = "none";
img.src = "plus.gif";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvParentGrid" runat="server" DataKeyNames="CountryId" Width="300"
AutoGenerateColumns="false" OnRowDataBound="gvUserInfo_RowDataBound" GridLines="None" BorderStyle="Solid" BorderWidth="1px"  BorderColor="#df5015">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField ItemStyle-Width="20px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval("CountryID") %>');">
<img id="imgdiv<%# Eval("CountryID") %>" width="9px" border="0" src="plus.gif" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CountryId" HeaderText="CountryId" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="CountryName" HeaderText="CountryName" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("CountryID") %>" style="display: none; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false" BorderStyle="Double"  BorderColor="#df5015" GridLines="None" Width="250px">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="StateID" HeaderText="StateID" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="StateName" HeaderText="StateName" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Now add following namespaces in codebehind

C# Code


using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After that add following code in code behind


SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select TOP 4 CountryId,CountryName from Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvParentGrid.DataSource = ds;
gvParentGrid.DataBind();

}
protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
GridView gv = (GridView)e.Row.FindControl("gvChildGrid");
int CountryId = Convert.ToInt32(e.Row.Cells[1].Text);
SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + CountryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv.DataSource = ds;
gv.DataBind();
}
}
VB.NET Code


Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class VBSample
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
' This method is used to bind gridview from database
Protected Sub BindGridview()
con.Open()
Dim cmd As New SqlCommand("select TOP 4 CountryId,CountryName from Country", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gvParentGrid.DataSource = ds
gvParentGrid.DataBind()

End Sub
Protected Sub gvUserInfo_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
con.Open()
Dim gv As GridView = DirectCast(e.Row.FindControl("gvChildGrid"), GridView)
Dim CountryId As Integer = Convert.ToInt32(e.Row.Cells(1).Text)
Dim cmd As New SqlCommand("select * from State where CountryID=" & CountryId, con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
con.Close()
gv.DataSource = ds
gv.DataBind()
End If
End Sub
End Class
Demo


Download sample code attached



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

60 comments :

Anonymous said...

How can u save this one in excel file? thanks!

Anonymous said...

hi.. please help! how to export this one into EXCEL file.. need help badly.. :'( thanks!

Anonymous said...

please post how to export this to excel. thanks!

Unknown said...

Hi..
I like your blog very much. I am a beginner in asp.net. I have a gridview which shows the project names and it should have a expand/collapse. On expand it should have 3 linkutton for every project nested inside and on collapse it should close.
Please give the program soon.

Unknown said...

Please send a complete program to my id
chandanmb7@gmail.cm

Unknown said...

The Above code is looking Great
==================================

This code also contain the find control using the Cell Name


..

if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gv = (GridView)e.Row.FindControl("Gd_Specs");
Label lblItemId = (Label)e.Row.Cells[0].FindControl("lblItemId");
int itemid = Convert.ToInt32(lblItemId.Text);

gv.DataSource = DataTableValue;
}


..
Good Day

Anonymous said...

I am not able to see child grid data. it shows blank no of lines that exist in state table.

Atul Agarwal said...

Hi,
I have buttons checboxes and textboxes inside the inner grid which I need to access.The inner grids get hidden on events.
Can you help me with the javascript to achieve the same?

Naseer's said...

Thanq, it working fine,but when we are raising any event like textchanged event in nested gridview, gridview is collapsing after the event is fired,how to make expand after the event is fired

Unknown said...

Nice article. Is it possible to show no plus image in the parent grid if there is no child data available? thanks.

Unknown said...

It's easy as 1..2...3, Thanks alot for the excellent post! :)

Anonymous said...

Above article is good. I am new to asp.net. I tried but i am getting error as 'DataSource' is not a member of 'gridview'

Anonymous said...

Hi,
please help! how to Add the data from one gridview to another gridview.Need help.( thanks!)

Anonymous said...

Hi,
how to implement 3 gridviews in one worksheet of excel.
Thank u.

Anonymous said...

hi
i am raju i want to update image in gridview please help me

Anonymous said...

hii... iwant to show data in gridview and my datasource is ms access the above code is showing error.

Unknown said...

hi this is naveen,,is it possible to drag and drop nested gridview,,,if yes please give me a suggestion

Anonymous said...

I am not able to see child grid data. it shows blank no of lines. Any Idea...

Anonymous said...

Hello Suresh...Can you tell me how to handle the child Gridview pageindexChanging Event in this above nested gridview example

Unknown said...

HI ,
Please tell me i want to do drag drop in nested gridview can any one tell me ?

Anonymous said...
This comment has been removed by a blog administrator.
Anonymous said...

It's working fine but when i am adding a link button into inside gridview and at the time of clicking this linkbutton gridview is collapsing .how do i keep expand always even after clicking the linkbutton and even page load also.

it's very urgent

thanks
Santosh

Rajiv Nayan said...
This comment has been removed by the author.
Rajiv Nayan said...

its working fine, but if i add link button in gvChildGrid then how can i found it using function not in row databound. Please help me ASAP.

Thanks Rajiv

Unknown said...

Mr. Suresh i just want a grid view with editable gridview and dropdown filter at every colomn.
Thanks

Anonymous said...

To display child gridview, javascript should be as follows (div.style.display = "block"):
if (div.style.display == "none") {
div.style.display = "block";
img.src = "minus.gif";
} else {
div.style.display = "none";
img.src = "plus.gif";
}

Anonymous said...

Thank you so much. this post is very useful.

Unknown said...

How do I change the data source to my own?
I will connect to an access database

Thanks

Anonymous said...

I have a similar grid and I am not able to achieve this! Can anyone help

Umesh said...

Superb Article.....

Anonymous said...

It was very helpful.
But I am trying to export the same to Excel.
but not able to see nested gridview in excel.
Any idea how can we export?

Unknown said...

Amazing Article.... It makes my app as super..!!

But Small fix in JS
function divexpandcollapse(divname)
{
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none")
{
img.src = "images/minus.gif";
div.style.display = "block";
}
else
{
img.src = "images/plus.gif";
div.style.display = "none";
}

}

Anonymous said...

Logically right but I'm facing problem with your representation of the article. Please modify it. e.g. use "pre" tag for the coding part. Thank You.

Unknown said...
This comment has been removed by the author.
Bharath said...

good one...helped me lot

Bharath said...

can anyone help (gridview (gridview(gridview))) 3 gridviews.

Bharath said...

please help me above one urgent...

Anonymous said...

Thanks Suresh, Is there any way by which i can load the inner grid view on expansion.

Unknown said...

thanks Suresh, it works for two level nesting of gridview. i need a three level nested gridview with edit and update on third level. edit is working fine for me but update is not picking edititemtemplate controls.

can u pls help me on the same.
thanks in advance.

Unknown said...

thanks Suresh

Anonymous said...

thats was excellent. thanks alot

Unknown said...

Thanks sir ur coding style helped me lot.

balaji said...

hello Sir its not getting man... You Forgot this One
protected void gvParentGrid_SelectedIndexChanged(object sender, EventArgs e)
{

}

Anonymous said...

This work very good. Do you have any suggestion in only loading the data for one item when child Gridview is expanded. This starts to load slow if have alot of data.

Anonymous said...

expand all collapse all gridview in asp.net

Unknown said...

my expand and collapse is not working can anybody help

Anonymous said...

dear sir,
is it possible to activate a help gridview within a gridview when i key in something in a textbox in a gridview. i have done this with flexgrid control in vb6

Anonymous said...

Dear Suresh Sir.
Nice Exp..

Unknown said...

Please help me out. I'm getting the following error!

Both DataSource and DataSourceID are defined on 'Parent'. Remove one definition.
gvParentGrid.DataSource = ds;
gvParentGrid.DataBind();
for the code:

Anonymous said...

Good Post.

Shiro said...

Thanks so much! Simple and easy to understand! XD

Unknown said...

could you please tell me same application with checkboxs in both parent and child gridview.

Unknown said...
This comment has been removed by the author.
Unknown said...

I have done same application with checkbox in both parent and child gridviews. But the problem is When I check any checkbox, gridviews was automatically collapsed. I would like to make selected gridview was in expanding mode, until to I collaps the row or expanding other new row.

Wajid Irshad said...

How to insert nested gridview data into database??????????

Amatya said...

Nice deed.. Keep it up :)

Vijay said...
This comment has been removed by the author.
Vijay said...

Nice Sir,
Can you please share
Javscript for SubGridview Textbox Null Validation

Unknown said...

nice article..

Unknown said...

Hi..
I like your blog very much. On expand i have edit button .when i click on edit button grid collapase.
Please give the solution asap.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.