Click here to Skip to main content
15,881,757 members
Articles / Web Development / XHTML
Article

Expanding / Collapsing GridView Rows

Rate me:
Please Sign up or sign in to vote.
4.69/5 (52 votes)
15 May 2008CPOL1 min read 299.8K   3.2K   102   60
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.NET
<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.NET
<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:

JavaScript
<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)


Written By
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:



Comments and Discussions

 
QuestionRe: Collapse/Expand panels Pin
S.Aijaz13-May-08 20:45
S.Aijaz13-May-08 20:45 
AnswerRe: Collapse/Expand panels Pin
Samir NIGAM14-May-08 18:34
Samir NIGAM14-May-08 18:34 
GeneralRe: Collapse/Expand panels Pin
S.Aijaz6-Jun-08 2:17
S.Aijaz6-Jun-08 2:17 
GeneralRe: Collapse/Expand panels Pin
S.Aijaz6-Jun-08 2:19
S.Aijaz6-Jun-08 2:19 
GeneralRe: Collapse/Expand panels Pin
Samir NIGAM6-Jun-08 19:36
Samir NIGAM6-Jun-08 19:36 
GeneralIts really good Pin
Islam ElDemery12-May-08 22:44
Islam ElDemery12-May-08 22:44 
GeneralRe: Its really good Pin
Samir NIGAM12-May-08 23:37
Samir NIGAM12-May-08 23:37 
GeneralGridExpert Pin
Srinath Gopinath12-May-08 19:06
Srinath Gopinath12-May-08 19:06 
Good article...Will it work if we enable autogeneratecolumns atribute of gridview?
GeneralRe: GridExpert Pin
Samir NIGAM12-May-08 23:39
Samir NIGAM12-May-08 23:39 
GeneralSo good Pin
amrsalah12-May-08 15:31
amrsalah12-May-08 15:31 
GeneralRe: So good Pin
Samir NIGAM12-May-08 17:41
Samir NIGAM12-May-08 17:41 
GeneralGrid View Guru... Pin
Abhijit Jana7-May-08 5:40
professionalAbhijit Jana7-May-08 5:40 
GeneralRe: Grid View Guru... Pin
Samir NIGAM7-May-08 17:54
Samir NIGAM7-May-08 17:54 
GeneralRe: Grid View Guru... Pin
Abhijit Jana7-May-08 18:17
professionalAbhijit Jana7-May-08 18:17 
GeneralRe: Grid View Guru... Pin
Abhijit Jana7-May-08 18:22
professionalAbhijit Jana7-May-08 18:22 
GeneralRe: Grid View Guru... Pin
Samir NIGAM7-May-08 18:49
Samir NIGAM7-May-08 18:49 
GeneralWOW! Pin
ACMA_19807-May-08 1:33
ACMA_19807-May-08 1:33 
GeneralRe: WOW! Pin
Samir NIGAM12-May-08 23:42
Samir NIGAM12-May-08 23:42 
GeneralGood Job Pin
24891287-May-08 1:27
24891287-May-08 1:27 
GeneralRe: Good Job Pin
Samir NIGAM12-May-08 23:42
Samir NIGAM12-May-08 23:42 
Generalfun with java script Pin
san_geit7-May-08 1:08
san_geit7-May-08 1:08 
GeneralRe: fun with java script Pin
Samir NIGAM7-May-08 1:10
Samir NIGAM7-May-08 1:10 
GeneralEvery Time I learn something new from your article. Pin
Sandeep Shekhar7-May-08 0:55
Sandeep Shekhar7-May-08 0:55 
GeneralRe: Every Time I learn something new from your article. Pin
Samir NIGAM7-May-08 1:09
Samir NIGAM7-May-08 1:09 
GeneralGood Job Pin
MCSDvikasmisra6-May-08 23:49
MCSDvikasmisra6-May-08 23:49 

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.