Click here to Skip to main content
11,649,522 members (78,062 online)
Click here to Skip to main content

Maintaining States of Selected CheckBoxes in Different Pages inside the GridView

, 25 Dec 2008 CPOL 119.4K 3.8K 127
Rate this:
Please Sign up or sign in to vote.
This article describes how to manage states of the Checkboxes inside the GridView in different pages.
Preview.gif

Introduction

Here, I am going to present how to maintain selected CheckBoxes’ states in different pages inside the GridViewcontrol.

Background

If you have a Gmail account then probably you have observed a great feature of maintaining selected CheckBoxesstates in different pages on Inbox Grid, i.e. suppose that you are in the first page of your Inbox & select some mails through CheckBoxes & move to the second page. You also select some mails there and further move to the next page. Finally you return back to the first/second page where you find that all the previously selected mails are already selected. This means that Gmail maintains all the selected mails’ states in deferent pages of Inbox Grid. Now if you select mails in different pages of the Inbox Grid & click Delete link, then only current page’s selected mails are deleted. But my clients wanted some more advanced features. Actually my client’s requirement was to delete all pages’ selected mails by clicking on Delete link. So I started to work on it & finally came up with this solution.

Implementation Details

To implement this functionality, I've divided it into three parts:

  • Selecting / Deselecting all the CheckBoxesInside a GridView.
    I've achieved this functionality using HeaderClick& ChildClickJavaScript methods.
  • Restoring selected CheckBoxesstates Inside a GridViewfor particular pages.
    I've achieved this functionality by invoking RestoreStatemethod in the window.onload event.
  • Storing selected CheckboxesRow-Ids.
    I've used HiddenField hdnFldSelectedValuesfor this purpose. It maintains Row-Ids of selected CheckBoxes’separated by ‘|’.

HTML Code

I have used a TemplateFieldinside the GridView& put a CheckBoxand a HiddenFieldin the ItemTemplateas well as another CheckBoxin the HeaderTemplateof the TemplateField. To identify each GridView Rowuniquely, I've used AutoIncrementcolumn in the datasource & bind it to the HiddenField hdnFldId. But it can be anything, e.g. row id from the database, etc.

<asp:GridView ID="gvCheckboxes" runat="server" 
	AutoGenerateColumns="False" AllowPaging="True"        
                  OnPageIndexChanging="gvCheckboxes_PageIndexChanging" 
			OnRowDataBound="gvCheckboxes_RowDataBound">
   <Columns>
      <asp:TemplateField HeaderText="Select">
         <ItemTemplate>
            <asp:CheckBox ID="chkBxSelect" runat="server" />
            <asp:HiddenField ID="hdnFldId" runat="server" Value='<%# Eval("Id") %>' />
         </ItemTemplate>
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
         <HeaderTemplate>
            <asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" 
		runat="server" />
         </HeaderTemplate>
      </asp:TemplateField>
         <asp:BoundField DataField="RandomNo" HeaderText="Random Number">
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
      </asp:BoundField>
      <asp:BoundField DataField="Date" HeaderText="Date">
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="75px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="75px" />
      </asp:BoundField>
      <asp:BoundField DataField="Time" HeaderText="Time">
         <HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="100px" />
      </asp:BoundField>
   </Columns>
   <RowStyle BackColor="Moccasin" />
   <AlternatingRowStyle BackColor="NavajoWhite" />
   <HeaderStyle BackColor="DarkOrange" Font-Bold="True" ForeColor="White" />
</asp:GridView>

I've also added a HiddenFiledin the page to keep track of Row-Ids of corresponding selected CheckBoxes.

<asp:HiddenField ID="hdnFldSelectedValues" runat="server" />

Attaching Click Events

I've attached onclick eventon header CheckBoxas:

<asp:CheckBox ID="chkBxHeader" 
	onclick="javascript:HeaderClick(this);" runat="server" />

I've also attached onclick eventon each Row-CheckBoxthrough RowDataBound eventof the GridViewas:

if (e.Row.RowType == DataControlRowType.DataRow && 
	(e.Row.RowState == DataControlRowState.Normal ||
                e.Row.RowState == DataControlRowState.Alternate))
{
   CheckBox chkBxSelect = (CheckBox)e.Row.Cells[0].FindControl("chkBxSelect");
   CheckBox chkBxHeader = (CheckBox)this.gvCheckboxes.HeaderRow.FindControl
				("chkBxHeader");
   HiddenField hdnFldId = (HiddenField)e.Row.Cells[0].FindControl("hdnFldId");
   chkBxSelect.Attributes["onclick"] = string.Format
                                       (
                                         "javascript:ChildClick(this,document.
					getElementById('{0}'),'{1}');",            
                                          chkBxHeader.ClientID, hdnFldId.Value.Trim()
                                       );
}

Page’s window.onload Event

I've used window.onload eventto initialize global variables as well as to restore the previous states of all CheckBoxesin a particular column inside the GridView.

//Reference of the GridView. 
var TargetBaseControl = null;
//Total no of checkboxes in a particular column inside the GridView.
var CheckBoxes;
//Total no of checked checkboxes in a particular column inside the GridView.
var CheckedCheckBoxes;
//Array of selected item's Ids.
var SelectedItems;
//Hidden field that will contain string of selected item's Ids separated by '|'.
var SelectedValues;
        
window.onload = function()
{
   //Get reference of the GridView. 
   try
   {
      TargetBaseControl = document.getElementById('<%= this.gvCheckboxes.ClientID %>');
   }
   catch(err)
   {
      TargetBaseControl = null;
   }
            
   //Get total no of checkboxes in a particular column inside the GridView.
   try
   {
      CheckBoxes = parseInt('<%= this.gvCheckboxes.Rows.Count %>');
   }
   catch(err)
   {
      CheckBoxes = 0;
   }
            
   //Get total no of checked checkboxes in a particular column inside the GridView.
   CheckedCheckBoxes = 0;
            
   //Get hidden field that will contain string of selected item's Ids separated by '|'.
   SelectedValues = document.getElementById('<%= this.hdnFldSelectedValues.ClientID %>');
            
   //Get an array of selected item's Ids.
   if(SelectedValues.value == '')
      SelectedItems = new Array();
   else
      SelectedItems = SelectedValues.value.split('|');
                
   //Restore selected CheckBoxes' states.
   if(TargetBaseControl != null)
      RestoreState();
}

GridView’s Header Checkbox’s Click Event

This eventgets fired whenever GridView’sheader CheckBoxis clicked. In this event, states of all Row-CheckBoxesis changed depending upon the state of the header CheckBoxas well as Id of each Row is maintained in the SelectedItems arrayif header CheckBoxis checked, else removed from the SelectedItems array. Values of SelectedValues HiddenField & CheckedCheckBoxescounter are also updated in this event.

function HeaderClick(CheckBox)
{            
    //Get all the control of the type INPUT in the base control.
    var Inputs = TargetBaseControl.getElementsByTagName('input');
            
    //Checked/Unchecked all the checkBoxes in side the GridView & 
    //modify selected items array.
    for(var n = 0; n < Inputs.length; ++n)
        if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect',0) >= 0)
        {
            Inputs[n].checked = CheckBox.checked;
            if(CheckBox.checked)
                SelectedItems.push(document.getElementById(Inputs[n].id.replace
			('chkBxSelect','hdnFldId')).value);
            else
                DeleteItem(document.getElementById(Inputs[n].id.replace
			('chkBxSelect','hdnFldId')).value);
        }
                        
    //Update Selected Values. 
    SelectedValues.value = SelectedItems.join('|');
                        
    //Reset Counter
    CheckedCheckBoxes = CheckBox.checked ? CheckBoxes : 0;
}

GridView’s Rows Checkboxes’s Click Event

This eventgets fired whenever any CheckBoxof GridView’sRows CheckBoxesis clicked. In this event, first CheckedCheckBoxescounter is updated & state of the header CheckBoxis changed accordingly. After that entry for Row-Idcontaining this particular ChecBoxis maintained/removed in/from the SelectedItems array. Then value of SelectedValues HiddenFieldis updated from the SelectedItems array.

function ChildClick(CheckBox, HCheckBox, Id)
{               
   //Modify Counter;            
   if(CheckBox.checked && CheckedCheckBoxes < CheckBoxes)
      CheckedCheckBoxes++;
   else if(CheckedCheckBoxes > 0) 
      CheckedCheckBoxes--;
                
   //Change state of the header CheckBox.
   if(CheckedCheckBoxes < CheckBoxes)
      HCheckBox.checked = false;
   else if(CheckedCheckBoxes == CheckBoxes)
      HCheckBox.checked = true;
                
   //Modify selected items array.
   if(CheckBox.checked)
      SelectedItems.push(Id);
   else
      DeleteItem(Id);
                
   //Update Selected Values. 
   SelectedValues.value = SelectedItems.join('|');
}

RestoreState Method

This method is invoked in the window.onload event. This method is basically used to restore the previous states of all CheckBoxesin a particular column inside the GridViewin deferent pages. If the entry of a particular CheckBoxis found in the SelectedItems array, then its state becomes checked. After that state of the header CheckBoxis also updated.

function RestoreState()
{
   //Get all the control of the type INPUT in the base control.
   var Inputs = TargetBaseControl.getElementsByTagName('input');
            
   //Header CheckBox
   var HCheckBox = null;
            
   //Restore previous state of the all checkBoxes in side the GridView.
   for(var n = 0; n < Inputs.length; ++n)
      if(Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf('chkBxSelect',0) >= 0)
         if(IsItemExists(document.getElementById(Inputs[n].id.replace
		('chkBxSelect','hdnFldId')).value) > -1)
         {
            Inputs[n].checked = true;          
            CheckedCheckBoxes++;      
         }
         else
            Inputs[n].checked = false;   
      else if(Inputs[n].type == 'checkbox' && 
		Inputs[n].id.indexOf('chkBxHeader',0) >= 0) 
         HCheckBox = Inputs[n];  
                    
   //Change state of the header CheckBox.
   if(CheckedCheckBoxes < CheckBoxes)
      HCheckBox.checked = false;
   else if(CheckedCheckBoxes == CheckBoxes)
      HCheckBox.checked = true;  
}

DeleteItem Method

This method is used to remove an entry for a particular CheckBoxfrom the SelectedItems array.

function DeleteItem(Text)
{
   var n = IsItemExists(Text);
   if( n > -1)
      SelectedItems.splice(n,1);
}

IsItemExists Method

This method is used to check whether an entry for a particular CheckBoxexists in the SelectedItems arrayor not.

function IsItemExists(Text)
{
   for(var n = 0; n < SelectedItems.length; ++n)
      if(SelectedItems[n] == Text)
         return n;
                 
      return -1;  
}

Deleting Selected Items From Different Pages

Now finally to delete all selected CheckBoxesin all different pages. Simply get all the selected Ids & delete selected items using appropriate method in the Link's/Button'sdelete eventhandler as:

protected void btnDelete_Click(object sender, EventArgs e)
{
   //Get Ids
   string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');
   
   //Code for deleting items
   foreach (string Item in IDs)
   {
      //Call appropriate method for deletion operation.
   }
}

Conclusion

So this is my solution. If you have some other ideas about this functionality, please share them with me.

Supporting Browsers

I have tested this functionality using the following browsers:

Browsers.png

History

  • 18th December, 2008 -- Original version posted
  • 26th December, 2008 -- Article updated

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

 
QuestionMaintaining States of Selected CheckBoxes in Different Pages inside the GridView Pin
DNYANESHWAR KAWATHE6-Jul-12 3:15
memberDNYANESHWAR KAWATHE6-Jul-12 3:15 
i have download and run ur application of maintaining state of checkboxes successfully,but i have problem when using in content page ,ContentHolder page of master page is within updatepanel tag and ajaxtoolkit used on master page. "Microsoft JScript runtime error: Object required" i had same script but excludding the part of script for maintaing state it is ok

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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
Web03 | 2.8.150804.4 | Last Updated 26 Dec 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid