Click here to Skip to main content
12,507,845 members (54,847 online)
Click here to Skip to main content
Add your own
alternative version


31 bookmarked

Expanding / Collapsing GridView Columns with Smooth Dynamic Effect

, 3 Jul 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article describes how to expand and collapse columns of a GridView using JavaScript


Last year I had posted an article: Expanding / Collapsing GridView Rows. In that article, I had described implementation details of Expanding / Collapsing rows of a GridView using JavaScript with smooth dynamic effect. Now through this article, I'm going to demonstrate how to expand and collapse columns of a GridView using JavaScript with smooth dynamic effect.

CSS Code

I've used the following CSS classes for this demo. Header and Footer CSS classes have been used for GridView’s header and footer rows respectively and Row and AlternateRow CSS classes for GridView’s normal and alternate rows respectively. Grid CSS class has been used for GridView’s background.


I've put these CSS classes in a separate StyleSheet.css file and attached its reference in the Grid.aspx page as follows:

<link href="CSS/StyleSheet.css" rel="stylesheet" type="text/css" />


Below is the HTML of the GridView that has been used for this demo. I've applied Header, Footer, Row & AlternateRow CSS classes in the GridView through HeaderStyle, FooterStyle, RowStyle and AlternatingRowStyle respectively. Grid CSS class is applied through the CssClass property of the GridView. I've taken TemplateField columns inside the GridView and put an Image control in HeaderTemplate of each TemplateField column.

<asp:GridView ID="gvTab" CssClass="Grid" runat="server" AutoGenerateColumns="False"
                                   ShowFooter="True" GridLines="Vertical">
            <asp:Image ID="imgN" onclick="javascript:Toggle(this,0);" 
			runat="server" ImageUrl="~/Images/minus.gif"
                           	ToolTip="Collapse" ImageAlign="AbsMiddle" />
            <asp:Label ID="lblHeaderN" runat="server" Text="n"></asp:Label>
            <asp:Label ID="lblItemN" runat="server" Text='<%# Eval("n") %>'></asp:Label>
         <HeaderStyle Width="50px" />
         <ItemStyle Width="50px" />
           <asp:Image ID="imgSqrt" onclick="javascript:Toggle(this,1);" 
		runat="server" ImageUrl="~/Images/minus.gif"
                  	ToolTip="Collapse" ImageAlign="AbsMiddle" />
           <asp:Label ID="lblHeaderSqrt" runat="server" Text="sqrt(n)"></asp:Label>
           <asp:Label ID="lblItemSqrt" runat="server" Text='<%# Eval("sqrtn") %>'>

Attaching click Event

I've attached click event on header Image of each GridView column as:

<asp:Image ID="imgSqrt" onclick="javascript:Toggle(this,1);" 
	runat="server" ImageUrl="~/Images/minus.gif"
         ToolTip="Collapse" ImageAlign="AbsMiddle" />

Page’s window.onload Event

I've used window.onload event to initialize global variables.

var Grid = null;
var UpperBound = 0;
var LowerBound = 1;
var CollapseImage = 'Images/minus.gif';
var ExpandImage = 'Images/plus.gif';
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');

GridView’s Header Image’s Click Event

This event gets invoked on successive clicks on any one header Image. This event first toggles the header Image and then toggles the requested column of the GridView by invoking the ToggleImage and ToggleColumns methods respectively.

function Toggle(Image, Index)
    ToggleImage(Image, Index);  
    ToggleColumns(Image, Index);

The first argument is the reference of the Image to be clicked while the second argument is the column index of the GridView that contains the particular Image.

ToggleImage Method

This method is invoked from the Toggle method. The basic function of this method is to toggle the source as well as tooltip of the selected header Image.

function ToggleImage(Image, Index)
    if(Image.IsExpanded == undefined || Image.IsExpanded)
        Image.src = ExpandImage;
        Image.title = 'Expand';
        n = UpperBound;
        Image.IsExpanded = false;
        Image.src = CollapseImage;
        Image.title = 'Collapse';
        n = LowerBound;
        Image.IsExpanded = true;

ToggleColumns Method

The first time this method is invoked from the Toggle method, after that it is invoked by itself recursively, using the setTimeout method. I've invoked it recursively here in order to create a smooth dynamic effect during the expanding/collapsing of the GridView columns.

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

I've used here JavaScript closure to invoke ToggleColumns method recursively with arguments through setTimeout method.

function ToggleColumns(Image, Index)
   if (n < LowerBound || n > UpperBound) return;

   var Condition = Rows[n].getElementsByTagName('td')[Index].style.visibility == '';
   Condition = Condition || Rows[n].getElementsByTagName('td')
				[Index].style.visibility = 'visible'; 
   Rows[n].getElementsByTagName('td')[Index].style.visibility = 
				Condition ? 'hidden' : 'visible';

   if(Image.IsExpanded) n++; else n--;

   setTimeout(function(){ToggleColumns(Image, Index);},TimeSpan);

Winding Up

I have toggled visibility of all TD elements of a GridView column in order to create an illusion of smooth dynamic effect with the help of setTimeout method through recursion. Different browsers have different effects of Expanding / Collapsing GridView Columns. In Internet Explorer 7/8, Safari, Google Chrome and Opera, it seems that columns are Expanding / Collapsing while in case of Mozilla, Firefox and Netscape Navigator, it seems that column’s text are Expanding / Collapsing.

Supporting Browsers

I have tested this code on the following browsers:



  • 4th July, 2009 -- Original version posted


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


About the Author

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,.


You may also be interested in...


Comments and Discussions

QuestionGridview Row Index Pin
hideepak12-Jul-12 0:08
memberhideepak12-Jul-12 0:08 
QuestionHow to use this in Master Page Pin
chayna18-Jan-10 17:48
memberchayna18-Jan-10 17:48 
GeneralSuggestion.. Pin
Ambalavanar Thirugnanam18-Sep-09 4:58
memberAmbalavanar Thirugnanam18-Sep-09 4:58 
GeneralPlaying with Gridview Pin
Abhijit Jana8-Jul-09 5:18
mvpAbhijit Jana8-Jul-09 5:18 
GeneralRe: Playing with Gridview Pin
Samir NIGAM11-Jul-09 19:08
mvpSamir NIGAM11-Jul-09 19:08 
Generalgood Article Pin
Viral Upadhyay5-Jul-09 19:56
memberViral Upadhyay5-Jul-09 19:56 
GeneralRe: good Article Pin
Samir NIGAM5-Jul-09 22:44
mvpSamir NIGAM5-Jul-09 22:44 
Generali know every one gonna ask the same question Pin
Member 15911274-Jul-09 22:22
memberMember 15911274-Jul-09 22:22 
GeneralRe: i know every one gonna ask the same question Pin
Samir NIGAM5-Jul-09 22:50
mvpSamir NIGAM5-Jul-09 22:50 
QuestionWhy? Pin
zlezj3-Jul-09 22:16
memberzlezj3-Jul-09 22:16 
AnswerRe: Why? Pin
Paul Selormey3-Jul-09 22:24
memberPaul Selormey3-Jul-09 22:24 
GeneralRe: Why? Pin
Member 10727193-Jul-09 23:17
memberMember 10727193-Jul-09 23:17 
GeneralRe: Why? Pin
spoodygoon4-Jul-09 4:07
memberspoodygoon4-Jul-09 4:07 
GeneralRe: Why? Pin
Samir NIGAM5-Jul-09 23:05
mvpSamir NIGAM5-Jul-09 23:05 
GeneralRe: Why? Pin
Samir NIGAM5-Jul-09 22:57
mvpSamir NIGAM5-Jul-09 22:57 
GeneralRe: Why? Pin
Samir NIGAM5-Jul-09 22:54
mvpSamir NIGAM5-Jul-09 22:54 
AnswerRe: Why? Pin
Viral Upadhyay5-Jul-09 20:02
memberViral Upadhyay5-Jul-09 20:02 
GeneralRe: Why? Pin
Samir NIGAM5-Jul-09 23:06
mvpSamir NIGAM5-Jul-09 23:06 
AnswerRe: Why? Pin
Samir NIGAM5-Jul-09 22:53
mvpSamir NIGAM5-Jul-09 22:53 

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
Web01 | 2.8.160927.1 | Last Updated 4 Jul 2009
Article Copyright 2009 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid