Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET and Web » GridView Inside GridView

GridView Inside GridView

An article on how to use GridView control available in ASP.Net 2.0 having multiple controls in template inside it.

Total page views :  87855
Total downloads :  1290
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewInSideGridView.zip
 
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor

Introduction

This article is very useful to all the users who are working with ASP.Net 2.0 GridView control. Here I am explaining how to work with GridView control in ASP.Net 2.0 which is very easier then DataGrid Control in ASP.Net 1.1. I will also explain what are the differences in GridView and Datagrid Control in ASP.Net 1.1. I want to explain how to work with template column having datagrid inside.

Background

The basic idea behind this article is to workout with ASP.Net 2.0's GridView Control than the DataGrid Control in ASP.Net 1.1. As I had worked with DataGrid Control so I knew how difficult to work with it in same project. I had done almost same project in ASP.Net 1.1 also. But to work with ASP.Net 2.0 GridView control is too good, easy and very user friendly. Though I had faced lot of difficulties in this but still I can say it is far better then ASP.Net 1.1's grid control for some functionality. GridView control gives you Edit, Update, Delete, Sorting, Selection and Paging facility built in.

Using the code

Here in this project, I have used ObjectDataSource control for binding the GridView to the data. This is one of the best features available in VS.Net 2005. It is very easy to work with it.

The main difference between DataGrid and GridView control is that the first one has central event handling which means any event raised by control inside the DataGrid's template column will be handled by ItemCommand event of datagrid. But this functionality is some what different in GridView Control. It directly calls the handler of the control.

I mean to say that in GridView Control if you have added one template column having GridView inside it and now if you select "Column Sorting" command then it will not call any event of Master grid. It will directly call the sorting handler of the child grid. It is up to the user to take advantage of this feature.

So let me explain the code now. Here I have one MasterTable which is bind to the Master Grid using MasterDataSouce and one ChildTable which is bind to Gridview inside template column of Mastergird. To bind the Child Grid to ChildDataSource we have to use RowDataBound event which is called every time when each row from database is bind to the Grid View's row.

Here, basic idea behind caching is that when cell value is required you should get it and show it. So what happen behind the screen is:

RowDataBound event of Mastergrid

Protected Sub grdMaster_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdMaster.RowDataBound

        Dim objListItem As DataControlRowState

        objListItem = e.Row.RowState

        Dim intMAsterID1 As Integer

        If e.Row.RowType = DataControlRowType.DataRow Then

            Dim grd As GridView

            If objListItem = 5 Then

                grd = CType(e.Row.FindControl("grdChildGridEdit"), GridView)

                MasterTableID = Convert.ToInt32(CType(e.Row.DataItem, DataRowView).Row.ItemArray(0).ToString())

                intMAsterID1 = MasterTableID

            ElseIf objListItem = DataControlRowState.Normal Or objListItem = DataControlRowState.Alternate Then

                grd = CType(e.Row.FindControl("grdChildGridNormal"), GridView)

                intMAsterID1 = Convert.ToInt32(CType(e.Row.DataItem, DataRowView).Row.ItemArray(0).ToString())

                Dim lnkButtton As LinkButton

                lnkButtton = CType(e.Row.FindControl("Edit"), LinkButton)

                If lnkButtton IsNot Nothing Then

                    lnkButtton.CommandName = "Edit Master"

                    lnkButtton.CommandArgument = intMAsterID1.ToString

                End If

            ElseIf objListItem = DataControlRowState.Edit Then

                grd = CType(e.Row.FindControl("grdChildGridEdit"), GridView)

                MasterTableID = Convert.ToInt32(CType(e.Row.DataItem, DataRowView).Row.ItemArray(0).ToString())

                intMAsterID1 = MasterTableID

            End If

            If grd IsNot Nothing Then

                grd.DataSourceID = ""

                grd.DataSource = ChildDataSource

                ChildDataSource.SelectParameters("MasterTableID").DefaultValue = intMAsterID1

                ChildDataSource.Select()

                grd.DataBind()

            End If

        End If

 

End Sub

Here what I am doing is when master table's each row bind with the GridView's row I am finding the ChildGrid Control then binding that control with ChildDataSource for that MasterID.

Above code will be used when user hits on Master Grid Edit button. So In the Template Column child grid with edit and delete option will get visible. Now, the biggest problem with this child grid is that each and every event you to write manually because grid will lost it's binding when any command is get fired. And another thing is that unlike ASP.Net1.1's datagrid child grid's handler will get called when any command of childgird get fired like Edit, Delete, Sorting, Paging. In ASP.Net1.1 Data grid's Inner control's event will be first handled by Grid's Item Command event irrespective of whether that control is DataGrid, Button, List Box etc. But here it will not call the RowCommand event of Master Grid it will directly call RowCommand event of ChildGrid. So event flow is like this

1. When User Press Edit Command is Master Grid it will call RowCommand Event of MasterGrid with Command Name as "Edit".

2. Now it will call RowDataBound of Mastergrid here you will find the whether the RowState of particular Row is edit then you will find ChildGrid with Edit and Delete Command in the EditTempalate of Template Column. And Bind the grid to ChildDataSource.

3. Now, MasterGrid will look like below:

4. When you press EditCommand of ChildGrid it will RowCommand of ChildGrid unlike ASP.Net1.1 's Datagrid call the ItemCommand of Mastergrid. And it will not call the RowDataBound of MasterGrid so your child edit grid for that particular row will not bind to datasource. So your grid will get disappear. Now, here you in RowCommand of child grid you have to rebind the grid with the datasource.

grdchildgrid = CType(sender, GridView)

If e.CommandArgument IsNot Nothing Then

        If IsNumeric(e.CommandArgument) Then

             intRowId = Convert.ToInt32(e.CommandArgument)

        End If

End If

If e.CommandName.Equals("Edit") Then

        grdchildgrid.DataSourceID = ""

        grdchildgrid.DataSource = ChildDataSource

        ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

        ChildDataSource.Select()

End If

If e.CommandName.Equals("Update") Then

        UpdateChildRecord()

        grdchildgrid.DataSourceID = ""

        grdchildgrid.DataSource = ChildDataSource

        ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

        ChildDataSource.Select()

End If

If e.CommandName.Equals("Delete") Then

        DeleteChildRecord()

        grdchildgrid.DataSourceID = ""

        grdchildgrid.DataSource = ChildDataSource

        ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

        ChildDataSource.Select()

End If

If e.CommandName.Equals("Cancel") Then

        grdchildgrid.DataSourceID = ""

        grdchildgrid.DataSource = ChildDataSource

        ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

        ChildDataSource.Select()

End If

If e.CommandName.Equals("Page") Then

        grdchildgrid.EditIndex = -1

        grdchildgrid.DataSourceID = ""

        grdchildgrid.DataSource = ChildDataSource

        ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

        ChildDataSource.Select()

End If

If e.CommandName.Equals("Sort") Then

       grdchildgrid.EditIndex = -1

       Dim dt As DataView

       grdchildgrid.DataSourceID = ""

       ChildDataSource.SelectParameters("MasterTableID").DefaultValue = MasterTableID

       dt = CType(ChildDataSource.Select(), DataView)

       If ViewState.Item("SortDirection") IsNot Nothing Then

            If CType(ViewState.Item("SortDirection"), SortDirection) = SortDirection.Ascending Then

                 dt.Sort = e.CommandArgument & "  ASC"

                 ViewState.Item("SortDirection") = SortDirection.Descending

            Else

                 dt.Sort = e.CommandArgument & "  DESC"

                 ViewState.Item("SortDirection") = SortDirection.Ascending

            End If

       End If

       grdchildgrid.DataSource = dt

       grdchildgrid.DataBind()

End If

Here you will find that you have to handle every command manually for the child grid because you are continuously changing binding of child grid. And one thing I have found that if you did not write handler of edit, delete, update, sort, page command it will give error because when you press Edit Command of Child Grid it will find for the RowEditing Handler of child grid even if you are doing your all the activity in RowCommand event.

5. Here one thing is important is that in RowCommand event of Child Grid you will get the old values in the grid means viewstate of the grid. But the childgrid will not be bind to any data source if you don't bind it to in  RowCommand event.

6. When you press UpdateCommand it will call RowCommand with CommandArgument as "Update". And after it will call the RowUpdating event of the ChildGrid. But there no values will be there in either e.NewValues or e.OldValues. 

Points of Interest

ASP.NET 2.0 is very good to work with. It is so much enhanced version and very much handy to work.

MSDN LINK

History

This is first version of GridControl. I will release few more interesting articles on ASP.Net 2.0. If any body has any typical problem in Datagrid I will try to work out on that.


Login to add your contents and source code to this article
 About the author
 
Nikhil
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
GridViewInSideGridView.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
SqlDatasource ? by Newbie On June 21, 2006

Hi

Can this be done using Sqldatasource ? Would you be able to provide some guidance here ?

TIA

Reply | Email | Delete | Modify | 
Export nested gridviews by Newbie On August 24, 2006

Hi Nikhil

I've successfully done the nested gridview. I'd like to be able to export it ? How would I go about this ?

TIA

Reply | Email | Delete | Modify | 
sorting,editing and Deleting In GridView Which use Grouping by mayank On February 9, 2007
how do i apply with using VB code
Reply | Email | Delete | Modify | 
i have doubt in gridview2.0 by mohan On April 25, 2007
hi iam mohan i have doubt in dridview control . in real time enviroment grirdview control wizard update,delete,paging,sorting events are working or not ? please tell me code for update,delete ,sorting ,paging in girdview 2.0 control .i am waiting for ur reply. thank you, mohan
Reply | Email | Delete | Modify | 
It's amazing by Alok On March 11, 2008
This is great article on gridview's different functionality. I want to know the email id of this article Mr. Nikhil . Thanks Nikhil for sharing this article with us.
Reply | Email | Delete | Modify | 
Give me a small example by Alok On March 11, 2008
Suppose there are 5 columns in a gridview . we want to update and delete function on gridview.how could i write code for that. i write the code as below but it show as error ---------------------------- protected sub GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) int s4 = (int)GridView1.DataKeys[e.RowIndex].Value string ss1 = "delete from dept where emp_id='" + s4 + "'" //delete(ss1) adc.delete(ss1) GridView1.EditIndex = -1 show_grid(); protected sub GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) TextBox t1, t2, t3 = new TextBox() t1 = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0] string s1 = Convert.ToString(t1.Text) t2 = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0] string s2 = t2.Text t3 = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0] string s3 = t3.Text int s4 = (int)GridView1.DataKeys[e.RowIndex].Value string ss = "update dept set dept_id='" + t1.Text + "',dept_name='" + t2.Text + "',dept_acc='" + t3.Text + "' where emp_id='"+s4+"'" update(ss) GridView1.editIndex = -1 show_grid()
Reply | Email | Delete | Modify | 
Hi Nikhil ,I hav a small problem. Can u solve it?Plz mail the solution .. by Alok On March 11, 2008
I have a gridview which contains 5 columns named date,code,type,name,detailed . I want to make rowupdating function n rowdeleting function on that gridview . can u write a code for that ? The first 4 fields are in a table & code is the p.key n there is a another table which contains code & detailed . PLZ SEND THE CODE TO MY MAIL.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.