home » articles » Maintaining States of Selected CheckBoxes in Different Pages inside the GridView

Maintaining States of Selected CheckBoxes in Different Pages inside the GridView

change text size: A A A

11/4/2009 by samir.nigam

Download the sample application - 4.23 KB

 

Introduction

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

Background

If you have a Gmail account then probably you have observed a great feature of maintaining selected CheckBoxes states 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 CheckBoxes Inside a GridView.
    I've achieved this functionality using HeaderClick & ChildClick JavaScript methods.
•  Restoring selected CheckBoxes states Inside a GridView for particular pages.
    I've achieved this functionality by invoking RestoreState method in the window.onload event.
•  Storing selected Checkboxes Row-Ids.
    I've used HiddenField hdnFldSelectedValues for this purpose. It maintains Row-Ids of selected CheckBoxes’   separated by ‘|’.
 
HTML Code

I have used a TemplateField inside the GridView & put a CheckBox and a HiddenField in the ItemTemplate as well as another CheckBox in the HeaderTemplate of the TemplateField. To identify each GridView Row uniquely, I've used AutoIncrement column 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 HiddenFiled in 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 event on header CheckBox as:

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


I've also attached onclick event on each Row-CheckBox through RowDataBound event of the GridView as:

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 event to initialize global variables as well as to restore the previous states of all CheckBoxes in 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 event gets fired whenever GridView’s header CheckBox is clicked. In this event, states of all Row-CheckBoxes is changed depending upon the state of the header CheckBox as well as Id of each Row is maintained in the SelectedItems array if header CheckBox is checked, else removed from the SelectedItems array. Values of SelectedValues HiddenField & CheckedCheckBoxes counter 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 event gets fired whenever any CheckBox of GridView’s Rows CheckBoxes is clicked. In this event, first CheckedCheckBoxes counter is updated & state of the header CheckBox is changed accordingly. After that entry for Row-Id containing this particular ChecBox is maintained/removed in/from the SelectedItems array. Then value of SelectedValues HiddenField is 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 CheckBoxes in a particular column inside the GridView in deferent pages. If the entry of a particular CheckBox is found in the SelectedItems array, then its state becomes checked. After that state of the header CheckBox is 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 CheckBox from the SelectedItems array.

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 CheckBoxes in all different pages. Simply get all the selected Ids & delete selected items using appropriate method in the Link's/Button's delete event handler 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.

 

“This article has been re-published from - Original Article

To rate this article please register or login

Author

samir.nigam samir.nigam (Member since:10/22/2009)

Comments (no comments yet)

Post a comment

Comment (No HTML)  

Type the characters:
 *
 
   

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest Articles

  • Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.
  • I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on various browsers and it works fine.
  • As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind there is question arise what is PagedDataSource. PagedDataSource is a class which encapsulates
  • So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.
  • So this is the approach that I've adopted to solve the Hover Delay problem. Although originally I developed Hover Delay to deactivate the click event for 1 second on a GridView row, later I also used Hover Delay to deactivate Drag n Drop of GridView rows. Kindly let me know if any one has some other better or different solution.
  • In this article I will explain how to import data from EXCEL to SQL in ASP.NET . In many situations we have data in the form of excel sheet but we have the requirement to have that data in SQL SERVER DB. I have explained importing data both from Excel 97-2003 as well as Excel 2007 format.
  • The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
  • That’s all about this technique. Just download the sample application and happy CSS! I have tested this application on various browsers and it worked fine.
  • This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].
  • This Article is used to insert a numeric value on the sever control(text box) This is a java script code for the the client side validation. On Page Load Event You can change the events in txtNoOfQuestion.Attributes.Add("onkeypress", "return numericOnly(this);"); like onfocus events like other according to needs.
  • 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 Exp
  • In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.
  • Introduction I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are check
  • This article describes how to toggle the states of all CheckBoxes inside a particular DataGridView column.
  • This article describes how to apply client-side mouse over & mouse out effects on the GridView’s rows.