Click here to Skip to main content
12,396,961 members (58,169 online)
Click here to Skip to main content
Add your own
alternative version

Stats

206.4K views
2.8K downloads
101 bookmarked
Posted

Expanding / Collapsing GridView Rows

, 15 May 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes how to expand and collapse rows of a GridView using JavaScript.

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)

Share

About the Author

Samir NIGAM
Technical Lead Infogain India Pvt Ltd
India India

Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.

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, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.

Awards:


You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Member 1011252325-Jun-13 15:14
memberMember 1011252325-Jun-13 15:14 
QuestionNeed Some Clarifications Pin
CSR896-Jun-13 20:12
memberCSR896-Jun-13 20:12 
QuestionGood work... but one doubt Pin
Anu Palavila13-Oct-11 22:49
memberAnu Palavila13-Oct-11 22:49 
AnswerRe: Good work... but one doubt Pin
Member 1011252325-Jun-13 15:13
memberMember 1011252325-Jun-13 15:13 
GeneralGreat wok but i have a question. Pin
MK87_200831-May-11 4:18
memberMK87_200831-May-11 4:18 
GeneralMy vote of 5 Pin
Marcio_Coelho1-Feb-11 8:20
memberMarcio_Coelho1-Feb-11 8:20 
GeneralMy vote of 5 Pin
SChristmas31-Jan-11 22:05
memberSChristmas31-Jan-11 22:05 
GeneralRe: Grid is null or not an object Pin
Samir NIGAM5-Jul-09 23:08
mvpSamir NIGAM5-Jul-09 23:08 
GeneralExpanding / Collapsing GridView Rows placed in another grid Pin
kurapati's21-May-09 19:09
memberkurapati's21-May-09 19:09 
QuestionHow about with a regular HTML table? Pin
afenn21-May-09 11:27
memberafenn21-May-09 11:27 
Questionhow to make one column expand/collapse keeping other one fixed in gridview? Pin
Member 215679126-Jan-09 12:40
memberMember 215679126-Jan-09 12:40 
GeneralMaintain State of GridView on PostBack Pin
timchimento8-Dec-08 6:24
membertimchimento8-Dec-08 6:24 
QuestionNice work. Pin
Member 45768475-Oct-08 5:10
memberMember 45768475-Oct-08 5:10 
GeneralGood Job Pin
proark22-Sep-08 22:46
memberproark22-Sep-08 22:46 
QuestionHow we make this grid nested Pin
Rehan Hussain13-Jun-08 1:22
memberRehan Hussain13-Jun-08 1:22 
GeneralCollapsing the rows Pin
Member 435482911-Jun-08 21:03
memberMember 435482911-Jun-08 21:03 
GeneralRe: Collapsing the rows Pin
SAMir Nigam 11-Jun-08 21:15
member SAMir Nigam 11-Jun-08 21:15 
QuestionGridLines getting washed out on first expand !!!! Pin
Prash28-May-08 0:34
memberPrash28-May-08 0:34 
AnswerRe: GridLines getting washed out on first expand !!!! Pin
SAMir Nigam 28-May-08 18:43
member SAMir Nigam 28-May-08 18:43 
GeneralNice One Pin
Satya Kanithi19-May-08 6:00
memberSatya Kanithi19-May-08 6:00 
GeneralRe: Nice One Pin
SAMir Nigam 19-May-08 18:05
member SAMir Nigam 19-May-08 18:05 
GeneralNice and simple implementation Pin
Antony M Kancidrowski15-May-08 0:35
memberAntony M Kancidrowski15-May-08 0:35 
GeneralRe: Nice and simple implementation Pin
SAMir Nigam 15-May-08 2:06
member SAMir Nigam 15-May-08 2:06 
Generalthanxxxxx Pin
snopbear13-May-08 3:44
membersnopbear13-May-08 3:44 
GeneralRe: thanxxxxx Pin
SAMir Nigam 13-May-08 17:45
member SAMir Nigam 13-May-08 17:45 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160721.1 | Last Updated 16 May 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid