Check Or Uncheck Checkboxes within GridView in ASP.NET using JQuery

No.of Views4270
Bookmarked0 times
Downloads 
Votes0
By  RRaveen   On  29 Dec 2010 10:12:57
Tag : JQuery , Grid Controls
Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Today I have implemented to my project to check and uncheck all checkboxes within gridview in asp.net. So in this article we focus how to implement this features using JQuery with less code. And also I have given live demonstration as well you can try it in live.

Implementation

    Let's we have 10 rows in gridview with first column to select user each rows to perform operation. On this time user can’t check each check box to select, because its consume time and it is not good user friendly system as well.
So I have implemented to features to select all checkbox or deselect all checkboxes in one click using a common check box. Even let’s say I have 10 records with checkboxes, but user want to select 5, 8 and 10. With less number of click and also without refresh page. Please try live demo end of the this article.

Let’s walk step by step to implement it.

Step 1

As usual create a new web project using visual studio 2008 and give name to project is “JQueryChkBox”.
Note: you can use any name to project.

Step 2

Add a GridView with few columns in page as like below,

Html Code

<asp:GridView ID="gvpub" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <asp:CheckBox runat="server" ID="chkAll" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox runat="server" ID="chkSelection" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="Name" HeaderText="Name" />
                    <asp:BoundField DataField="Address1" HeaderText="Address1" />
                    <asp:BoundField DataField="Address2" HeaderText="Country" />
                    <asp:BoundField DataField="Company" HeaderText="Company" />
                </Columns>
            </asp:GridView>

The first column has a template field to customize the header and row for this column. The header template will have a checkbox to check or uncheck checkboxes with one click. The item template will have checkbox for represent each row.

Step 3

Let’s create a simple data source to bind to grid view. This data source is custom object collection of the publishers.
Note: I have attached sample project end of this article you can download it.

C# Code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class checkanduncheckdemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<Publisher> collectionOfPub = new List<Publisher>();
            collectionOfPub.Add(new Publisher("Wrox", "No-02,John Ave 2", "US", "WROX"));
            collectionOfPub.Add(new Publisher("Apress", "No-03,Cels Ave 6", "US", "APRESS"));
            collectionOfPub.Add(new Publisher("Sams", "No-89,Test Ave 32", "US", "SAMS"));
            collectionOfPub.Add(new Publisher("Orelly", "No-23/08,John Ave 23", "US", "ORELLY"));
            collectionOfPub.Add(new Publisher("Packtpub", "No-56,John Ave 5", "INDIA", "PACKTPUB"));
            this.gvpub.DataSource = collectionOfPub;
            this.gvpub.DataBind();
        }


    }
}

Run and see output like shown,

 Output

Image Loading

Step 4
    In order work with JQuery, we have to add JQuery library in page as like bellow,
JavaScript

<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>

I'm always to prefer refer JQuery library source from Google CDN.

Step 5

Now write few lines of JavaScript code to access checkbox controls within gridview and implement features.

JavaScript

<script language="javascript">
    $(document).ready(function(){       
        var chkboxrow = "#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox";  
        var chkall =$("input[id$='chkAll']");  
        $(chkall).change(function(){     
            $(chkboxrow).each(function()
            {
            if($(this).is(':checked'))
            {
                $(this).attr('checked', false);
            }
            else 
            {
                 $(this).attr('checked', true);             
            }       
            });              
       });
    });

    </script>

Code Explanation

1.    The first line is defining document ready event for jquery.
2.    In the next line get all checkboxes within the gridview with id “chkselection” and type is checkbox.

var chkboxrow = "#<%=gvpub.ClientID%> input[id*='chkSelection']:checkbox";

3.    Next line is get the header checkbox with id is “chkAll” to perform the change event later part of the code.

var chkall =$("input[id$='chkAll']");

4.    Next line for register change event to the checkbox (header) and then loop each row checkbox and validate is checked or not, if not checked then check otherwise uncheck.

$(chkall).change(function(){     
            $(chkboxrow).each(function()
            {
            if($(this).is(':checked'))
            {
                $(this).attr('checked', false);
            }
            else 
            {
                 $(this).attr('checked', true);             
            }       
            });              
       });

5.    $(this).is(':checked') is help to verify a checkbox is checked or unchecked
6.    $(this).attr('checked', false); is used to set attibute “checked” is true or false. If true means its check else uncheck.
 

Step 6

Now run application and output like as shown below,

Image Loading

Live Demo

Check Or Uncheck Checkboxes within GridView

Download Sample Project 

Download source files -2 kb

Conclusion

In this article I have shared with how to check or uncheck checkboxes within gridview using JQuery and also with this article I have given live demonstration example, so you can try it in live and understand through the real world example. Thank you for reading, hopes help.

 
Sign Up to vote for this article
 
About Author
 
RRaveen
Occupation-Software Engineer
Company-TGS
Member Type-Gold
Location-Singapore
Joined date-03 Jun 2009
Home Page-codegain.com
Blog Page-www.codegain.com
- B.Sc. degree in Computer Science. - 4+ years experience in Visual C#.net and VB.net - Obsessed in OOP style design and programming. - Designing and developing Network security tools. - Designing and developing a client/server application for sharing files among users in a way other than FTP protocol. - Designing and implementing GSM gateway applications and bulk messaging. - Windows Mobile and Symbian Programming - Having knowledge with ERP solutions
 
 
Other popularSectionarticles
    The JQuery is powerful client side JavaScript library. Today I’m going to show you how to create cascading DropDownList using JQuery with JSON in ASP.NET.I hope you are all heard about cascading DropDownList and how to use with AJAX tool kit
    Published Date : 07/Dec/2010
    In this article I will demonstration to how to validate whether to check at least one checkbox is checked in the Gridview in ASP.NET using JQuery. The JQuery is significant library to manipulate client html and css with less line of code.Before Jquery come up we have used the pure JavaScript to implement this features. I will give the JavaScript code as well in end of this article.
    Published Date : 30/Dec/2010
    In this article, I will explain how to sort custom objects array using JQuery. Let’s say you have array with custom objects, the custom object has few attributes as well, so in this case, you may need to sort objects with different order with specific attributes.
    Published Date : 12/Jan/2011
    The JQuery is powerful library to manipulate client side HTML, CSS, object and etc. On this article I will explain how to sort element within array using JQuery. In this demonstration I will show sort for string and numeric elements.
    Published Date : 11/Jan/2011
    Today I have introduced the new features for CodeGain article submit page to count characters for description textbox with JQuery on time. The character counter is support to users to display how many characters have entered and how many chars remaining in live.
    Published Date : 25/Dec/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top
</