Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

DataGrid inside a DataGrid

This tutorial will teach you how to place and bind a DataGrid inside another DataGrid. The binding of the inner DataGrid will be done depending on the row of the parent DataGrid.

On Monday, June 5th 2006 at 05:55 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.2 with 58 votes)
Contextual Ads
More ASP.NET Resources
Advertisement
In this tutorial we're going to make use of ASP.NET 2.0 (and Visual Studio 2005), however the code works with ASP.NET 1.1 without any changes.

Below you can see an example of a DataGrid that has another DataGrid in one of its columns; also called intrinsic or inner DataGrids. We're going to build something similar in this ASP.NET tutorial.

DataGrid

Start by creating the ASPX code needed for the DataGrids. In our example the first DataGrid (the container) is named dgParents while the child DataGrid is named dgChildren. The second DataGrid (dgChildren) will reside in one of DataGrid's columns. Let's see the code:


<asp:DataGrid ID="dgParents" runat="server" CellPadding="6" BorderWidth="0" AutoGenerateColumns="False" OnItemDataBound="dgParents_ItemDataBound">

<Columns>

<asp:BoundColumn DataField="CatID" HeaderText="Category ID"></asp:BoundColumn>

<asp:BoundColumn DataField="CatName" HeaderText="Category Name"></asp:BoundColumn>

<asp:TemplateColumn HeaderText="Children Categories">

    <ItemTemplate>

        <asp:DataGrid ID="dgChildren" runat="server" CellPadding="6" BorderWidth="0" AutoGenerateColumns="False">

            <Columns>

                <asp:BoundColumn DataField="CatID" HeaderText="Category ID "></asp:BoundColumn>
                <asp:BoundColumn DataField="CatName" HeaderText="Category Name"></asp:BoundColumn>

            </Columns>

        </asp:DataGrid>

    </ItemTemplate>

</asp:TemplateColumn>

</Columns>

</asp:DataGrid>


As you can see, we are first creating one DataGrid with 3 columns. The first two columns show two fields from the database, while the third is more special - it is a TemplateColumn column which contains the second DataGrid inside it, dgChildren.

Now you are probably wondering how can we access dgChildren and DataBind it. Well, when the parent DataGrid gets bounded to a data source, each time a new row is added, the OnItemDataBound event fires. That's when we can access that row's instance of dgChildren. If you look closely you will notice that we already defined the OnItemDataBound attribute (in bold) to point to the event in our source code.

But first, let's switch to code view and bind the first DataGrid. You probably already have your own code for this, but here is something you could use as a sample:


SqlConnection SqlCon1 = new SqlConnection("Data Source=localhost;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=sa;Password=1234");

SqlCommand SqlCom1 = new SqlCommand("SELECT CatID, CatName FROM Categories", SqlCon1);

if (SqlCon1.State != ConnectionState.Open)

{

    SqlCon1.Open();

}

dgParents.DataSource = SqlCom1.ExecuteReader();

dgParents.DataBind();

SqlCon1.Close();


Nothing magic here, simply databinding the DataGrid control to the content of a SQL table. The magic happens when we go to the OnItemDataBound event of the parent DataGrid.
It would be very simple to just bind the inner DataGrid to a random data source in our tutorial, however in real-life you'll probably not want that. Most of the time you'll want to bind the inner DataGrid depending on the content of the container DataGrid's row. For example if you are listing the categories of a directory in the main DataGrid, you'll want to display subcategories (child categories) of each main category in the inner DataGrids. If this is stored in a database, you'll want the inner DataGrid to be aware of what row it is in. For example if it is in the row displaying "Financial Services", you'll want to retrieve subcategories of "Financial Services" and display them using the inner DataGrid. To do that in our current sample we're going to retrieve the CatID value from the parent DataGrid.


protected void dgParents_ItemDataBound(object sender, DataGridItemEventArgs e)

{

    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

    {
        SqlConnection SqlCon2 = new SqlConnection("Data Source=localhost;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=sa;Password=1234");

        SqlCommand SqlCom2;

        int CatID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "CatID"));

 

        DataGrid dgChildren = (DataGrid)e.Item.FindControl("dgChildren");

        SqlCom2 = new SqlCommand("SELECT CatID, CatName FROM Categories WHERE CatParent = " + CatID, SqlCon2);

        if (SqlCon2.State != ConnectionState.Open)

        {

            SqlCon2.Open();

        }

        dgChildren.DataSource = SqlCom2.ExecuteReader();

        dgChildren.DataBind();

        SqlCon2.Close();

    }

}


The first thing we do inside ItemDataBound (event which fires each time a new row is added to the DataGrid) is to create a new SQL connection and SQL command object. However, please note that for the sake of simplicity, we've done that here, however in a real-life application you'll probably look to optimize this, at least by declaring these objects outside of the event.

Then we check to see if the row is actually a row (ListItemType.Item) or alternating row (ListItemType.AlternatingItem), otherwise we're not interested in the content of that row. Inside CatID we store the CatID value from the container (parent) DataGrid; as we discussed above, this will help us retrieve the subcategories, since we'll pass this value into the SQL query.

On line number 9, another interesting thing happens. Since we can't access the inner DataGrid directly, we need to declare it first and assign it to the inner DataGrid that we created inside the container DataGrid, and we do this by using the FindControl() method.

The next lines are typical for every data binding process: the query is executed and the parent category ID is passed so that children of these category are retrieved, the SQL connection is opened, and the command is executed.

This is all you need know for creating inner DataGrids. If you experience problems with adapting this with your own data source, look carefully through the code and after you completely grasp the code, using inner DataGrids will become a routine task. Furthermore, this code can be applied to other controls, such as the Repeater control.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by sds on Monday, July 17th 2006 at 06:48 AM

dgfdgfdg

by Dhivya on Monday, July 17th 2006 at 06:50 AM

ya this seems to be a helpful and easy way to overview it

by DEEPAK on Friday, September 1st 2006 at 05:27 AM

Gr8, Excellent Work Andrei !!! Keep it Up

by puttu on Wednesday, October 25th 2006 at 12:43 AM

Nice stuff

by pam on Monday, December 4th 2006 at 05:27 AM

thats great!!!

by Nishant Kuamr on Tuesday, December 5th 2006 at 05:06 AM

Excellent.... quite simple ... really excellent
Thanks a lot for providing such a gr8 article

by Larry on Tuesday, February 27th 2007 at 12:50 PM

This is very useful and practical as well. Thanks

by JEP on Wednesday, March 14th 2007 at 02:53 PM

Is there a way to access the ItemDataBound Event of the inner grid? I need to make my inner grids editable with templated columns.

by Andrei Pociu on Wednesday, March 14th 2007 at 03:52 PM

Yes. At the point where you bind the child DataGrid:

dgChildren.DataSource = SqlCom2.ExecuteReader();
dgChildren.DataBind();

...also add aItemDataBound event handler, such as dgChildren_ItemDataBound:

dgChildren.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(dgChildren_ItemDataBound);

by Ravi Pinnoju on Thursday, May 10th 2007 at 07:02 AM

Thanks a lot for posting this articale.

by joey on Sunday, June 17th 2007 at 07:45 PM

is it possible to sort on the column that contains the datagrid?

by koteswararao on Wednesday, July 11th 2007 at 02:38 AM

hi

u r tought is very nice,but i have dought here ,u have mentoned same table,i con\\\'t get correct tought.

dont mine in my program i have taken emp,dept tables.how to bind these two .when i select deptno in emp talbe i want dept details like deptname,dloc.

iam waiting for u r reply.

bye

by vichu on Wednesday, September 26th 2007 at 03:56 AM

I is very simple and easy to understand.But i have one doubt please help me.

I have a id,name in the parent grid when i click that parent's grid name or id at that time the corresponding id of the child grid will display the complete employee details.

for example if i click id =1 in the parent grid now the child grid will display the full details of that corresponding employee details... please help me...
advance thanks..

I am waiting for your reply.

by vichu on Wednesday, September 26th 2007 at 05:34 AM

I is very simple and easy to understand.But i have one doubt please help me.

I have a id,name in the parent grid when i click that parent's grid name or id at that time the corresponding id of the child grid will display the complete employee details.

for example if i click id =1 in the parent grid now the child grid will display the full details of that corresponding employee details... please help me...
advance thanks..

I am waiting for your reply.

by Jem Smith on Thursday, October 4th 2007 at 07:42 PM

Hi
Good article and helpful to all

Regards
Infoseek Software Systems

by Neelam on Friday, October 26th 2007 at 07:50 AM

Very simple and easy to learn.
thanks for such a great effort!!
http://www.epurplemedia.co.uk/

by shrek professional on Saturday, October 27th 2007 at 05:05 PM

thanks alot it's helpful

by Bishwajit Sahoo on Monday, November 19th 2007 at 05:11 AM

Hi,
This code may be useful, but I have trid this but I am not able to view the datas fo inner/child datagrid.
Please solve my problem.

Thank you.

by Bishwajit Sahoo on Monday, November 19th 2007 at 06:17 AM

Hi Andrei,

Thanks a lot, your code is working effectively.

But if I want to doesnot show the header of child/inner datagrid, How I can do that?
Please help me.

by root123 on Saturday, February 16th 2008 at 03:53 AM

very clearly defined codes. Thanks !

by Software development on Monday, February 18th 2008 at 07:06 AM

Its quite useful ..Thanks a lot .. Please share more ..

by Softweb Solutions In on Friday, February 22nd 2008 at 03:29 AM

Thanks

Regards
Arpit Kothari
SEO Expert
http://www.softwebsolutions.com

by Elfi on Friday, April 18th 2008 at 01:26 PM

Its so useful.. Thanks a lot...

by Remeshkumar on Thursday, June 12th 2008 at 11:03 PM

Ecelent..very simple...thanks...

by Faisal on Monday, September 8th 2008 at 01:50 PM

What if there are control in child Datagrid like Link button or anyother. How to create a event trigger for that control.

by jayakumar on Wednesday, September 10th 2008 at 08:26 AM

Please send Inner Grid Controls Asp.net aspx.vb

by GOOD on Monday, September 15th 2008 at 12:41 AM

NICE

by Qureshi on Friday, December 26th 2008 at 05:06 AM

Thank you Andrew Pociu :)

by dsa on Friday, December 26th 2008 at 05:41 AM

dsfs

by dgdg on Sunday, January 25th 2009 at 02:21 AM

gjhgjhj

by vijay on Monday, March 9th 2009 at 05:36 AM

thats something beyond the practise....nice one.

by Sivaraman on Friday, May 1st 2009 at 08:30 AM

Really Very Good, Fanastic. I would like to appreciate u. Congrats.

by Sivaraman on Thursday, May 7th 2009 at 09:09 AM

Hi all,

I want to show the footer of the Child grid at the time of cliking a button in a row ( of parent datgrid) can anybody help me...

Thanks in advance

by Sivaraman on Thursday, May 7th 2009 at 09:13 AM

I tried with the following code parentGrid_ItemCommand Event

Dim i_ChildGrid As System.Web.UI.WebControls.DataGrid
i_ChildGrid = CType(e.Item.FindControl("ChilGrid"), System.Web.UI.WebControls.DataGrid)
i_ChildGrid.ShowFooter = True

But I m not getting the Footer of the Child DataGrid Plz help me

by salini on Friday, July 10th 2009 at 06:12 AM

Its so useful.. but I have trid this but I am not able to paging child datagrid

by salini on Friday, July 10th 2009 at 06:13 AM

Its so useful.. but I have trid this but I am not able to paging child datagrid

by pluto on Wednesday, September 9th 2009 at 05:56 AM

I think this is one of the third class article on nested gridview. U should have some sense of coding bastard

by pluto on Wednesday, September 9th 2009 at 05:56 AM

I think this is one of the third class article on nested gridview. U should have some sense of coding bastard

by Ajit on Wednesday, September 23rd 2009 at 04:03 AM

Very Nice

by Betty on Friday, October 9th 2009 at 03:23 PM

Hi,

I would like to have the grand child datagrid inside of the child datagrid. Would you please let me know how? I try yours then I successful for 2 level, how about 3 level?

by mani on Monday, November 23rd 2009 at 07:34 AM

thank you it useful for me i wil try to workout this pgm

by apoorv :-) on Friday, April 23rd 2010 at 06:27 AM

This particular article is really very nice and somewhere mapping the industry standards as well.
The article has tried well to draw the user's eye and has set an expandable platform to think more upon the given scenario.
keep up the good work .....


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs ASP.NET Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia

Other Resources