Click here to Skip to main content
6,594,432 members and growing! (16,696 online)
Email Password   helpLost your password?
Web Development » ASP.NET Controls » Grid Controls     Intermediate License: The Code Project Open License (CPOL)

Expanding / Collapsing GridView Rows

By Samir NIGAM

This article describes how to expand and collapse rows of a GridView using JavaScript.
C# (C# 2.0), Javascript, CSS, HTML, XHTML, .NET (.NET 2.0), ASP.NET, ADO.NET, WebForms, Ajax, Dev
Posted:7 May 2008
Updated:15 May 2008
Views:50,174
Bookmarked:78 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
41 votes for this article.
Popularity: 7.25 Rating: 4.49 out of 5

1
1 vote, 2.4%
2
1 vote, 2.4%
3
8 votes, 19.5%
4
31 votes, 75.6%
5

preview.gif

Introduction

This article presents expand/collapse functionality for GridView rows using JavaScript. To demonstrate this functionality, I’ve used an Image on the GridView header. Rows of the GridView will expand and collapse on successive clicks on this Image.

Using the HTML code

Add a TemplateField inside the GridView and put an Image in the HeaderTemplate of the TemplateField. The HTML code for the GridView will look like this:

<asp:GridView ID="gvTab" BackColor="WhiteSmoke" runat="server" 
     AutoGenerateColumns="False" GridLines="Vertical" ShowFooter="True">
   <Columns>
      <asp:TemplateField>
         <HeaderStyle Width="25px" />
         <ItemStyle Width="25px" BackColor="White" />
         <HeaderTemplate>
            <asp:Image ID="imgTab" onclick="javascript:Toggle(this);" 
                 runat="server" ImageUrl="~/minus.gif" ToolTip="Collapse" />
         </HeaderTemplate>
      </asp:TemplateField>
      <asp:BoundField HeaderText="n" DataField="n">
         <HeaderStyle Width="25px" />
         <ItemStyle Width="25px" />
      </asp:BoundField>
      <asp:BoundField HeaderText="sqrt(n)" DataField="sqrtn">
         <HeaderStyle Width="150px" />
         <ItemStyle Width="150px" />
      </asp:BoundField>
      <asp:BoundField HeaderText="qbrt(n)" DataField="qbrtn">
         <HeaderStyle Width="150px" />
         <ItemStyle Width="150px" />
      </asp:BoundField>
   </Columns>
   <HeaderStyle Height="25px" Font-Bold="True" BackColor="DimGray" 
                ForeColor="White" HorizontalAlign="Center"
                VerticalAlign="Middle" />
   <RowStyle Height="25px" BackColor="Gainsboro" 
             HorizontalAlign="Center" VerticalAlign="Middle" />
   <AlternatingRowStyle Height="25px" BackColor="LightGray" 
             HorizontalAlign="Center" VerticalAlign="Middle" />
   <FooterStyle BackColor="Gray" />
</asp:GridView>

Attach an onclick event to the GridView header’s Image.

<asp:Image ID="imgTab" onclick="javascript:Toggle(this);" runat="server" 
           ImageUrl="~/minus.gif" ToolTip="Collapse" />

Using the JavaScript code

Put the following code in the script tag:

<script type="text/javascript">
 var Grid = null;
 var UpperBound = 0;
 var LowerBound = 1;
 var CollapseImage = 'minus.gif';
 var ExpandImage = 'plus.gif';
 var IsExpanded = true;   
 var Rows = null;
 var n = 1;
 var TimeSpan = 25;
        
 window.onload = function()
 {
    Grid = document.getElementById('<%= this.gvTab.ClientID %>');
    UpperBound = parseInt('<%= this.gvTab.Rows.Count %>');
    Rows = Grid.getElementsByTagName('tr');
 }
        
 function Toggle(Image)
 {
    ToggleImage(Image);
    ToggleRows();  
 }    
        
 function ToggleImage(Image)
 {
    if(IsExpanded)
    {
       Image.src = ExpandImage;
       Image.title = 'Expand';
       Grid.rules = 'none';
       n = LowerBound;
             
       IsExpanded = false;
    }
    else
    {
       Image.src = CollapseImage;
       Image.title = 'Collapse';
       Grid.rules = 'cols';
       n = UpperBound;
                
       IsExpanded = true;
    }
 }
        
 function ToggleRows()
 {
    if (n < LowerBound || n > UpperBound)  return;
                            
    Rows[n].style.display = Rows[n].style.display == '' ? 'none' : '';
    if(IsExpanded) n--; else n++;
    setTimeout("ToggleRows()",TimeSpan);
 }
</script>

In the above code, global variables have been initialized in the window.onload event. There are three methods: Toggle, ToggleImage, and ToggleImage. The Toggle method is invoked on successive clicks on the header Image. This method first toggles the header image and then toggles the rows of the GridView by invoking the ToggleImage and ToggleImage methods. Note that the ToggleRows method is invoked here recursively, using the setTimeout method. I’ve invoked it recursively here in order to create a dynamic effect during the expanding/collapsing of the GridView rows.

In order to make a delay in each recursion, each call to the ToggleRows method has been delayed for 25 milliseconds. You can change it by altering the TimeSpan value depending on your needs.

Conclusion

In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.

I have tested this script on the following browsers:

Browsers.png

License

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

About the Author

Samir NIGAM


Member

SAMIR NIGAM is the Tech Lead at Axero Solutions LLC. He is a CodeProject MVP 2009, a Microsoft Certified Technology
Specialist (MCTS)
as well as a Microsoft Certified Professional Developer (MCPD)
in C# for web-based applications. He is an insightful IT professional with
results-driven comprehensive technical skill having rich, hands-on work experience
in web-based applications using ASP.NET, C#, AJAX, Microsoft
Enterprise Library
, MS SQL Server 2005.


He has earned his master degree (MCA) from U.P. Technical University, Lucknow,
INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and
Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics)
from University of Allahabad, Allahabad, INDIA.


He has good knowledge of Object Oriented Programming, 3-Tier Architecture
and Algorithm Analysis & Design as well as good command over cross-browser
client side programming using JavaScript.

Awards:


Contact: nigam.samir@hotmail.com
Occupation: Team Leader
Company: Axero Solutions LLC
Location: India India

Other popular ASP.NET Controls articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 53 (Total in Forum: 53) (Refresh)FirstPrevNext
GeneralGrid is null or not an object Pinmembergunasundari22:07 5 Jul '09  
GeneralRe: Grid is null or not an object PinmvpSamir NIGAM0:08 6 Jul '09  
GeneralExpanding / Collapsing GridView Rows placed in another grid Pinmemberkurapati's20:09 21 May '09  
QuestionHow about with a regular HTML table? Pinmemberafenn12:27 21 May '09  
Generalhow to make one column expand/collapse keeping other one fixed in gridview? PinmemberMember 215679113:40 26 Jan '09  
GeneralMaintain State of GridView on PostBack Pinmembertimchimento7:24 8 Dec '08  
QuestionNice work. PinmemberMember 45768476:10 5 Oct '08  
GeneralGood Job Pinmemberproark23:46 22 Sep '08  
GeneralHow we make this grid nested PinmemberRehan Hussain2:22 13 Jun '08  
GeneralCollapsing the rows PinmemberMember 435482922:03 11 Jun '08  
GeneralRe: Collapsing the rows Pinmember SAMir Nigam 22:15 11 Jun '08  
QuestionGridLines getting washed out on first expand !!!! PinmemberPrash1:34 28 May '08  
AnswerRe: GridLines getting washed out on first expand !!!! Pinmember SAMir Nigam 19:43 28 May '08  
GeneralNice One PinmemberSatya Kanithi7:00 19 May '08  
GeneralRe: Nice One Pinmember SAMir Nigam 19:05 19 May '08  
GeneralNice and simple implementation PinmemberAntony M Kancidrowski1:35 15 May '08  
GeneralRe: Nice and simple implementation Pinmember SAMir Nigam 3:06 15 May '08  
Generalthanxxxxx Pinmembersnopbear4:44 13 May '08  
GeneralRe: thanxxxxx Pinmember SAMir Nigam 18:45 13 May '08  
Generalstatus after postback Pinmemberpetr.snobelt1:02 13 May '08  
GeneralRe: status after postback Pinmember SAMir Nigam 18:59 13 May '08  
QuestionCollapse/Expand panels PinmemberS_Aijaz10:18 13 May '08  
AnswerRe: Collapse/Expand panels Pinmember Samir Nigam 0:41 13 May '08  
GeneralRe: Collapse/Expand panels PinmemberS_Aijaz10:45 13 May '08  
GeneralRe: Collapse/Expand panels Pinmember Samir Nigam 0:58 13 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 May 2008
Editor: Smitha Vijayan
Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2009
Web20 | Advertise on the Code Project