Click here to Skip to main content
14,775,673 members
Articles » Web Development » ASP.NET » Data
Posted 22 Feb 2011


162 bookmarked

Expandable Rows in GridView

Rate me:
Please Sign up or sign in to vote.
4.67/5 (64 votes)
4 Dec 2012CPOL
Add expandable rows to a GridView for master/detail view.



This article shows how to add functionality to the ASP.NET GridView control to allow the display of master/detail records with expanding rows. It probably isn't suited to scenarios where large number of records will be returned at a time.

This example is based on work I did for an equine hospital showing appointments where the cost of treatments had exceeded the limit agreed with the client. Expanding the details lists the transactions which make up the cost.


I was asked for this functionality by a client and found a few articles online presenting different solutions, but I found all of them to be overly-complex. However, some of those other solutions, such as this one, are more suitable for large record sets as my solution renders all of the details for each record when the page loads, rather than only when they are requested.

Using the Code

This solution doesn't require any special classes or custom controls, just a bit of JavaScript. It simply adds a new row after each existing row in the main (master) GridView in the RowDataBound event and creates an expanded details (detail) GridView inside it.

The code for the ASP page looks like this:

<asp:GridView ID="grdOverLimitList" runat="server" AutoGenerateColumns="False" 
  DataSourceID="SQLOverLimitList" CssClass="gridview" AllowSorting="True" 
  FooterStyle-CssClass="footer" >
  <AlternatingRowStyle CssClass="alternating"></AlternatingRowStyle>
        <%--This is a placeholder for the details GridView--%>
    <asp:BoundField DataField="PetID" HeaderText="Pet ID" SortExpression="Pet ID" />
    <asp:BoundField DataField="AppointmentID" HeaderText="Appointment ID" 
		SortExpression="AppointmentID" />
    <asp:BoundField DataField="Horse Name" HeaderText="Horse Name" 
		SortExpression="Horse Name" />
    <asp:BoundField DataField="Client Surname" HeaderText="Client Surname" 
		SortExpression="Client Surname" />
    <asp:BoundField DataField="Senior Clinician" HeaderText="Senior Clinician" 
		SortExpression="Senior Clinician" />
    <asp:BoundField DataField="Warning Limit" 
	HeaderText="Warning Limit" SortExpression="Warning Limit" />
    <asp:BoundField DataField="Cost" 
	HeaderText="Cost" SortExpression="Cost" />
    No data to display
  <FooterStyle CssClass="footer"></FooterStyle>
  <SortedAscendingHeaderStyle CssClass="sortedasc"></SortedAscendingHeaderStyle>
  <SortedDescendingHeaderStyle CssClass="sorteddesc"></SortedDescendingHeaderStyle>

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">

<asp:SqlDataSource ID="SQLOverLimitList" runat="server" 
  ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" 
  SelectCommand="sp_Equine_OverLimitList" SelectCommandType="StoredProcedure">

<asp:SqlDataSource ID="SQLOverLimitDetail" runat="server"
  ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
  SelectCommand="sp_Equine_OverLimitDetail" SelectCommandType="StoredProcedure">

That just sets up a simple GridView, which is the master table. Note that it includes an empty ItemTemplate column where the 'Show/Hide' button will go.

Next is the code behind for the RowDataBound event of this GridView:

Protected Sub grdOverLimitList_RowDataBound(ByVal sender As Object, _
	ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
	Handles grdOverLimitList.RowDataBound

  If e.Row.RowType = DataControlRowType.DataRow Then

    'Configure the datasource for the expanded details
    Dim appID As String = Convert.ToString(DataBinder.Eval_
	(e.Row.DataItem, "AppointmentID")) 'Get the unique ID for this record
    SQLOverLimitDetail.SelectParameters.Clear() 'Remove all select parameters 
				'from the datasource for the expanded details
    SQLOverLimitDetail.SelectParameters.Add("AppID", appID) 'Add the select parameter 
	'to the datasource for the expanded details using the unique ID of the record

    'Create a new GridView for displaying the expanded details
    Dim gv As New GridView
    gv.DataSource = SQLOverLimitDetail
    gv.ID = "grdSQLOverLimitDetail" & e.Row.RowIndex 'Since a gridview is 
	'being created for each row they each need a unique ID, so append the row index
    gv.AutoGenerateColumns = False
    gv.CssClass = "subgridview"
    AddHandler gv.RowDataBound, AddressOf grdOverLimitDetails_RowDataBound 'Add a 
					'rowdatabound method for the new GridView

    'Add fields to the expanded details GridView
    Dim bf1 As New BoundField
    bf1.DataField = "Date Added"
    bf1.DataFormatString = "{0:d}"
    bf1.HeaderText = "Date Added"

    Dim bf2 As New BoundField
    bf2.DataField = "Treatment"
    bf2.HeaderText = "Treatment"

    Dim bf3 As New BoundField
    bf3.DataField = "Total Cost"
    bf3.HeaderText = "Total Cost"
    bf3.DataFormatString = "{0:c}"

    'Create the show/hide button which will be displayed on each row of the main GridView
    Dim btn As Web.UI.WebControls.Image = New Web.UI.WebControls.Image
    btn.ID = "btnDetail"
    btn.ImageUrl = "~/Images/detail.gif"
    btn.Attributes.Add("onclick", "javascript: gvrowtoggle_
	(" & e.Row.RowIndex + (e.Row.RowIndex + 2) & ")") 'Adds the javascript 
	'function to the show/hide button, passing the row to be toggled as a parameter

    'Add the expanded details row after each record in the main GridView
    Dim tbl As Table = DirectCast(e.Row.Parent, Table)
    Dim tr As New GridViewRow(e.Row.RowIndex + 1, -1, _
	DataControlRowType.EmptyDataRow, DataControlRowState.Normal)
    tr.CssClass = "hidden"
    Dim tc As New TableCell()
    tc.ColumnSpan = grdOverLimitList.Columns.Count
    tc.BorderStyle = BorderStyle.None
    tc.BackColor = Drawing.Color.AliceBlue
    tc.Controls.Add(gv) 'Add the expanded details GridView to the newly-created cell
    tr.Cells.Add(tc) 'Add the newly-created cell to the newly-created row
    tbl.Rows.Add(tr) ' Add the newly-ccreated row to the main GridView
    e.Row.Cells(0).Controls.Add(btn) 'Add the show/hide button to the main GridView row

    gv.DataBind() 'Bind the expanded details GridView to its datasource

  End If

End Sub 

This is heavily annotated so hopefully it explains itself but it contains these basic steps:

  1. Clear the select parameters from the datasource for the details view and add a new one using the unique ID for the current record.
  2. Create a new GridView instance and specify its datasource, ID, CSS class and RowDataBound method. This will be our details GridView.
  3. Add bound fields to the new GridView.
  4. Create the show/hide button in the master record row, adding the 'OnClick' attribute to point to the JavaScript coming up below. Note that it is actually an image, not a button, to remove any question of postback.
  5. Create a new, empty row after the current row in the master GridView, then populate it with the new GridView, and add the show/hide button to the master record row.
  6. Bind the new GridView to its datasource.

You will notice that in creating the show/hide button, this code passes the index of the relevant details row (I know the formula looks a bit crazy, but trust me!) as the variable rows in the JavaScript below. This script is at the top of my ASP.NET page in the usual way.

<script type="text/javascript">

  function gvrowtoggle(row) {
    try {
      row_num = row; //row to be hidden
      ctl_row = row - 1; //row where show/hide button was clicked
      rows = document.getElementById('<%= grdOverLimitList.ClientID %>').rows; 
      rowElement = rows[ctl_row]; //elements in row where show/hide button was clicked
      img = rowElement.cells[0].firstChild; //the show/hide button

      if (rows[row_num].className !== 'hidden') //if the row is not currently hidden 
        rows[row_num].className = 'hidden'; //hide the row
        img.src = '../Images/detail.gif'; //change the image for the show/hide button
      else {
        rows[row_num].className = ''; //set the css class of the row to default 
				//(to make it visible)
        img.src = '../Images/close.gif'; //change the image for the show/hide button
    catch (ex) {alert(ex) }

Some pretty simple code, when the show/hide button is clicked this just checks the current class of the details row, setting it to 'hidden' if it's visible and setting it to the default class if it's hidden.

Finally, we just need to create a CSS class called 'hidden' which will hide the detail row until it's requested. I've also included my CSS for styling the GridViews, in case you're interested:

    display: none;

width: 100%;
border: 1px solid black;
background: white;
text-align: center;

.gridview th
text-align: center;
background: #013b82;
color: white;
.gridview .pager
text-align: center;
background: #013b82;
color: White;
font-weight: bold;
border: 1px solid #013b82;
.gridview .pager a
color: #666;

.gridview a
text-decoration: none;
color: White;
.gridview a:hover
color: Silver;
.gridview .sortedasc
background-color: #336699;
.gridview .sortedasc a
padding-right: 15px;
background-image :url(../images/up_arrow.png);
background-repeat: no-repeat;
background-position: right center;
.gridview .sortedasc a:hover
.gridview .sorteddesc
background-color: #336699;
.gridview .sorteddesc a
padding-right: 15px;
background-image :url(../images/down_arrow.png);
background-repeat: no-repeat;
background-position: right center;
.gridview .sorteddesc a:hover
.gridview .alternating
background: #d8d8d8;


border: none;
margin: 0px 0px 5px 25px;
background: whitesmoke;
.subgridview th
background: silver;
color: Black;

Points of Interest

There isn't anything particularly difficult about this, it just took some thinking through. The one thing that did drive me a bit mad was that, whereas in Firefox/Chrome the default style for a GridViewRow is 'table-row', in Internet Explorer it's 'block'. That's why in the JavaScript when the details row is being made visible, the className is left blank rather, causing the browser to use whatever is default.


  • 22nd February, 2011: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United Kingdom United Kingdom
IT Manager for a large higher education institution in the North West of England with responsibility and experience in everything from networking, systems administration, database administration, helpdesk support, web development, etc. since 2003.

I tend to develop web applications in ASP.NET and VB.NET, with a bit of JavaScript and C# thrown in for good measure at times.

Comments and Discussions

QuestionJavaScript Error: Function Expected Pin
Andrés Leiva22-Aug-16 7:59
MemberAndrés Leiva22-Aug-16 7:59 
QuestionPlease help me add one more level in gridview Pin
Member 418415010-Feb-16 11:26
MemberMember 418415010-Feb-16 11:26 
AnswerRe: Please help me add one more level in gridview Pin
Andrés Leiva22-Aug-16 8:00
MemberAndrés Leiva22-Aug-16 8:00 
QuestionIntegration Pin
Member 114920692-Mar-15 6:56
MemberMember 114920692-Mar-15 6:56 
QuestionRowCommand on detail grid Pin
Member 114920692-Mar-15 6:49
MemberMember 114920692-Mar-15 6:49 
QuestionMoar C# Please Pin
mw00t25-Mar-14 13:13
Membermw00t25-Mar-14 13:13 
Questionmaking Master grid editable Pin
Vaughnis5-Feb-14 9:33
MemberVaughnis5-Feb-14 9:33 
QuestionCode is posting back Pin
Member 786441018-Jan-14 4:51
MemberMember 786441018-Jan-14 4:51 
QuestionRecursive Expandable gridview Pin
Kumar Chandrashekhar Kashyap25-Oct-13 4:03
MemberKumar Chandrashekhar Kashyap25-Oct-13 4:03 
QuestionProblem with Expandable grid view Pin
srmohanr19-Oct-13 19:26
Membersrmohanr19-Oct-13 19:26 
GeneralMy vote of 5 Pin
freegiuliop8-Jul-13 23:22
Memberfreegiuliop8-Jul-13 23:22 
QuestionI converted the project to VB.NET Pin
Member 99274443-May-13 6:07
MemberMember 99274443-May-13 6:07 
QuestionRowDataBound for the Detail GridView Pin
Ekjon7-Mar-13 13:13
MemberEkjon7-Mar-13 13:13 
BugPaging & Mastergridview viewstate="true" problem Pin
Kashif.Khan.in11-Feb-13 1:19
MemberKashif.Khan.in11-Feb-13 1:19 
GeneralRe: Paging & Mastergridview viewstate="true" problem Pin
Kashif.Khan.in11-Feb-13 21:34
MemberKashif.Khan.in11-Feb-13 21:34 
QuestionSub Gridview minimizing on postback Pin
James Culpepper15-Jan-13 4:19
MemberJames Culpepper15-Jan-13 4:19 
QuestionTroble in RowCommand Pin
imchanchalsingh7-Jan-13 1:57
Memberimchanchalsingh7-Jan-13 1:57 
QuestionRowCommand trouble Pin
Member 848442421-Dec-12 3:53
MemberMember 848442421-Dec-12 3:53 
GeneralMy vote of 5 Pin
Varun Sareen10-Dec-12 19:19
professionalVarun Sareen10-Dec-12 19:19 
GeneralMy vote of 1 Pin
raj@aia10-Dec-12 18:07
Memberraj@aia10-Dec-12 18:07 
Suggestionpost source code Pin
jmohanbe6-Dec-12 23:30
Memberjmohanbe6-Dec-12 23:30 
GeneralMy vote of 5 Pin
maris984-Dec-12 9:59
Membermaris984-Dec-12 9:59 
GeneralMy vote of 5 Pin
Jitendra20054-Dec-12 8:14
MemberJitendra20054-Dec-12 8:14 
QuestionHow does Javascript function work? Pin
Corey Blair4-Dec-12 6:43
MemberCorey Blair4-Dec-12 6:43 
AnswerRe: How does Javascript function work? Pin
phil24154-Dec-12 7:17
Memberphil24154-Dec-12 7:17 

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.