Click here to Skip to main content
13,297,048 members (54,532 online)
Click here to Skip to main content
Add your own
alternative version


200 bookmarked
Posted 30 May 2006

Gridview Inside a GridView in ASP.NET 2.0

, 30 May 2006
Rate this:
Please Sign up or sign in to vote.
An article on how to use a GridView control in ASP.NET 2.0, having multiple controls in templates inside it.

Master and Chid GridView In Normal Mode


This article will be very useful to all users who are working with ASP.NET 2.0 GridView control. Here, I will explain how to work with the GridView control in ASP.NET 2.0, which is very easier to use than the DataGrid control in ASP.NET 1.1. I will also explain the differences between the GridView and the DataGrid controls. We will also look into how to work with a template column having a DataGrid inside it.


The basic idea behind this article is to see how much the ASP.NET 2.0's GridView control is easier to work than the DataGrid control in ASP.NET 1.1. I have previously worked with the DataGrid control, and I know how difficult it is to work with it in the same project in which I am using the GridView control. Working with the ASP.NET 2.0 GridView control is very easy as it is very user friendly. Though I had faced a lot of difficulties in using it, I can still say it is far better than the DataGrid control. The GridView control gives you Edit, Update, Delete, Sorting, Selection, and Paging functionality built-in.

Using the code

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

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

I mean to say that in the GridView control, if you add a template column having a GridView inside it and then if you select the Column Sorting command, it will not call any event of the master grid, but 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 a master table which is bind to the master grid using MasterDataSouce and a child table which is bound to a GridView inside a template column of the master grid. To bind the child grid to the ChildDataSource, we have to use the RowDataBound event which is called every time when a row from the database is bound to the GridView’s row.

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

RowDataBound event of the master grid

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, _
            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, _
            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, _
            intMAsterID1 = MasterTableID
        End If
        If grd IsNot Nothing Then
            grd.DataSourceID = ""
            grd.DataSource = ChildDataSource
               "MasterTableID").DefaultValue = intMAsterID1
        End If
    End If
End Sub

Here, what I am doing is when the master table's rows are bound with the GridView's row, I find the ChildGrid control and then bind that control with the ChildDataSource for that MasterID.

The above code will be used when the user hits on the Master Grid Edit button. So, in the template column, the child grid with the edit and the delete options will get visible. Now, the biggest problem with this child grid is that each and every event handler have to be written manually because the grid will lose its binding when any command gets fired. And another thing is that unlike the DataGrid, the child grid’s handler will get called when any command of the child grid gets fired like Edit, Delete, Sorting, or Paging. In the DataGrid, the inner control's event will be first handled by the grid's ItemCommand event irrespective of whether that control is a DataGrid, Button, or ListBox. But here it will not call the RowCommand event of the master grid, but will directly call the RowCommand event of the child grid. So, the event flow is like this:

  1. When the user presses the Edit option in the master grid, it will call the RowCommand event of the master grid with the command name "Edit".
  2. Now, it will call the RowDataBound of the master grid here. You will find whether the RowState of the particular row is "Edit", and then you will find the child grid with the Edit and Delete commands in the EditTemplate of the template column. And then you will bind the grid to ChildDataSource.
  3. Now, the master grid will look like below:

Master GridView in Edit Mode.

  1. When you press the Edit option of the child grid, it will invoke the RowCommand of the child grid just like a DataGrid calls the ItemCommand of the master grid. And it will not call the RowDataBound of the master grid so your child edit grid for that particular row will not bind to the datasource. So your grid will disappear. Now, in the RowCommand of the child grid, you have to rebind the grid with the data source.
    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
                "MasterTableID").DefaultValue = MasterTableID
    End If
    If e.CommandName.Equals("Update") Then
        grdchildgrid.DataSourceID = ""
        grdchildgrid.DataSource = ChildDataSource
                "MasterTableID").DefaultValue = MasterTableID
    End If
    If e.CommandName.Equals("Delete") Then
        grdchildgrid.DataSourceID = ""
        grdchildgrid.DataSource = ChildDataSource
                "MasterTableID").DefaultValue = MasterTableID
    End If
    If e.CommandName.Equals("Cancel") Then
        grdchildgrid.DataSourceID = ""
        grdchildgrid.DataSource = ChildDataSource
                "MasterTableID").DefaultValue = MasterTableID
    End If
    If e.CommandName.Equals("Page") Then
        grdchildgrid.EditIndex = -1
        grdchildgrid.DataSourceID = ""
        grdchildgrid.DataSource = ChildDataSource
               "MasterTableID").DefaultValue = MasterTableID
    End If
    If e.CommandName.Equals("Sort") Then
        grdchildgrid.EditIndex = -1
        Dim dt As DataView
        grdchildgrid.DataSourceID = ""
               "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") = _
                dt.Sort = e.CommandArgument & "  DESC"
                ViewState.Item("SortDirection") = _
            End If
        End If
        grdchildgrid.DataSource = dt
    End If

    Here, you will find that you have to handle every command manually, for the child grid, because you are continuously changing the binding of the child grid. And another thing I have found is that if you do not write the handlers for the Edit, Delete, Update, Sort, and Page commands, it will give an error because when you press the Edit command of the child grid, it will search for the RowEditing handler of the child grid even if you are doing all the activity in the RowCommand event.

    The grid will look like this:

Master and Child GridView in Edit Mode.

  1. Here, one thing that is important is that in the RowCommand event of the child grid, you will get the old values in the grid, from the viewstate of the grid. But the child grid will not be bound to any data source if you don't bind it to in the RowCommand event.
  2. When you press UpdateCommand, it will call the RowCommand with the CommandArgument as "Update". And after that, it will call the RowUpdating event of the child grid. But there will be no values in either e.NewValues or e.OldValues. So you will have to do the update in the RowCommand event.

Points of interest

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


I will release a few more interesting articles on ASP.NET 2.0. If any body has any problems using DataGrid control, please let me know and I will try to work on it.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Nikhil Contractor
Software Developer (Senior) Self Employed
India India
I am working as Software Profession in Sungard Offshore Services.Basically i have stared with Java,Java servlet and oracle then shifted to .Net.Since 3.5 years i am working in .Net.I am very much impressed with my one Project leader Mr.Deep Ambarkar.I have learnt so much things form him and i am very much thankful to him.

You may also be interested in...

Comments and Discussions

Questiongridview delete. Pin
Dharanesh B.R8-Jun-12 19:25
memberDharanesh B.R8-Jun-12 19:25 
QuestionAwesome Pin
Ravindra_Parcha11-Feb-12 21:58
memberRavindra_Parcha11-Feb-12 21:58 
GeneralMy vote of 1 Pin
Naveen_8824-Jan-12 1:36
memberNaveen_8824-Jan-12 1:36 
Generalthanks for this article Pin
aniketathalye17-Jan-12 8:15
memberaniketathalye17-Jan-12 8:15 
GeneralC# - version Pin
Sad Nadnahc10-Jul-11 21:58
memberSad Nadnahc10-Jul-11 21:58 
GeneralExcellent Sample - Thanks a ton! Pin
danschultz16-Mar-11 6:37
memberdanschultz16-Mar-11 6:37 
GeneralMy vote of 4 Pin
Pankaj_tiwari198826-Oct-10 0:57
memberPankaj_tiwari198826-Oct-10 0:57 
GeneralMy vote of 3 Pin
Pank's 198613-Oct-10 21:40
memberPank's 198613-Oct-10 21:40 
GeneralThree layer grid Pin
Binay Prasad10-Aug-10 22:40
memberBinay Prasad10-Aug-10 22:40 
Generallooking in c# Pin
patelvipul_be17-May-10 7:59
memberpatelvipul_be17-May-10 7:59 
Generalthks nick Pin
patelvipul_be17-May-10 7:54
memberpatelvipul_be17-May-10 7:54 
GeneralChild gridview editing on dynamically added nested gridview Pin
donit13-Jan-10 15:16
memberdonit13-Jan-10 15:16 
GeneralGridview Toolbar Pin
Member 46918169-Nov-09 19:48
memberMember 46918169-Nov-09 19:48 
Generalasp:checkbox issue to set width in a gridview column Pin
biswabhusan10-Jun-09 21:27
memberbiswabhusan10-Jun-09 21:27 
GeneralNice Article Pin
rahu_1229-Jun-09 0:21
memberrahu_1229-Jun-09 0:21 
Generalhi master Pin
mohammed mana21-Apr-09 14:01
membermohammed mana21-Apr-09 14:01 
GeneralRe: hi master Pin
Nikhil Contractor27-Apr-09 20:59
memberNikhil Contractor27-Apr-09 20:59 
GeneralPlease translate this code into C#? GridView inside GridView Pin
Member 248578024-Mar-09 22:12
memberMember 248578024-Mar-09 22:12 
GeneralRe: Please translate this code into C#? GridView inside GridView Pin
dharshinipriya29-Mar-09 23:28
memberdharshinipriya29-Mar-09 23:28 
GeneralPlease give me this data base script Pin
Member 39049751-Mar-09 20:45
memberMember 39049751-Mar-09 20:45 
Questionsorting algorithm Pin
sumaira manzoor10-Nov-08 18:17
membersumaira manzoor10-Nov-08 18:17 
QuestionC# code Pin
hvap10-Nov-08 13:56
memberhvap10-Nov-08 13:56 
QuestionHow to access a dropdownlist inside the child gridview. Pin
jophy philip9-Nov-08 22:17
memberjophy philip9-Nov-08 22:17 
Questionhow in win forms? ... Pin
DavidRRR6-Nov-08 4:50
memberDavidRRR6-Nov-08 4:50 
Generalhi thanks Pin
kamalDhillon21-Oct-08 2:35
memberkamalDhillon21-Oct-08 2:35 
GeneralRemoving Headertext for ChildGridview Pin
sukkureddy21-Aug-08 0:40
membersukkureddy21-Aug-08 0:40 
GeneralNeed help in nesting grid view Pin
mr_rajesh862-Jul-08 22:31
membermr_rajesh862-Jul-08 22:31 
GeneralHelp me add 1 combobox or dropdownlist in Gridview! Pin
msmalldog2-Jun-08 2:34
membermsmalldog2-Jun-08 2:34 
GeneralRe: Help me add 1 combobox or dropdownlist in Gridview! Pin
chandralekha4-Aug-08 2:24
memberchandralekha4-Aug-08 2:24 
Generalread article Pin
ADELASSI8-Apr-08 21:51
memberADELASSI8-Apr-08 21:51[^]
GeneralHi... I need this sample code in C#... Plz help me Pin
Member 37068146-Mar-08 0:21
memberMember 37068146-Mar-08 0:21 
Generalhi i need the sample code of grid view inside a grid view in with c# coding Pin
kartik19-Dec-07 2:11
memberkartik19-Dec-07 2:11 
GeneralVery nice example Pin
certuser7611-Oct-07 13:13
membercertuser7611-Oct-07 13:13 
GeneralRe: Very nice example Pin
Nikhil Contractor11-Oct-07 20:45
memberNikhil Contractor11-Oct-07 20:45 
GeneralVS2003 Version exists. Nice Article. Pin
Rajib Ahmed16-Sep-07 18:16
memberRajib Ahmed16-Sep-07 18:16 
QuestionHelp Regarding Item_Command in .Net 2005 Pin
Pushkar IT2-Jul-07 5:12
memberPushkar IT2-Jul-07 5:12 
GeneralThanks you save me... Pin
Oslec21-Jun-07 21:31
memberOslec21-Jun-07 21:31 
GeneralGridView editing inside GridView in 2.0 Pin
avananda reddys 12313-Jun-07 22:05
memberavananda reddys 12313-Jun-07 22:05 
GeneralTemplate columns disappearing on Update btn click event Pin
adi3695-Apr-07 7:28
memberadi3695-Apr-07 7:28 
Generalgrdchildgrid_RowCommand use Pin
drwebmonkey19-Mar-07 13:39
memberdrwebmonkey19-Mar-07 13:39 
GeneralNice Tutorial Pin
zubinkasad7-Mar-07 23:59
memberzubinkasad7-Mar-07 23:59 
QuestionExport to Excel Pin
TryinItOut28-Feb-07 3:38
memberTryinItOut28-Feb-07 3:38 
AnswerRe: Export to Excel Pin
rreddy.V27-May-07 22:29
memberrreddy.V27-May-07 22:29 
QuestionHi nice one Pin
Tamil_selvan27-Feb-07 0:24
memberTamil_selvan27-Feb-07 0:24 
GeneralGridview DropDownList Edit Template DataSource as DataTable Pin
Rob@ISU20-Feb-07 9:38
memberRob@ISU20-Feb-07 9:38 
GeneralInvalid object name 'MasterTable' Pin
mmai16-Nov-06 8:05
membermmai16-Nov-06 8:05 
GeneralRe: Invalid object name 'MasterTable' Pin
mike aka9-Sep-07 7:42
membermike aka9-Sep-07 7:42 
GeneralGrid View in a GridView Pin
imDeepesh2-Nov-06 1:02
memberimDeepesh2-Nov-06 1:02 
GeneralQuestion Pin
ravenholm17-Aug-06 22:22
memberravenholm17-Aug-06 22:22 
GeneralGridView with Dynamic Column Addition [modified] Pin
codeprojectpragati25-Jun-06 5:10
membercodeprojectpragati25-Jun-06 5:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 30 May 2006
Article Copyright 2006 by Nikhil Contractor
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid