Click here to Skip to main content
15,885,782 members
Articles / Programming Languages / C#
Tip/Trick

Check all checkboxes in GridView using jQuery

Rate me:
Please Sign up or sign in to vote.
2.50/5 (5 votes)
2 Aug 2013CPOL 83.3K   14   7
Check all checkboxes in GridView using jQuery.

Introduction

This is the very basic need when you do bulk operations like email sending, export to excel, delete record etc. from a list. A CheckBox in header on which checked or unchecked all the CheckBoxes in the list should change respectively. Similar thing you can see in Gmail, Hotmail etc. which have more variations to select record.

In this tutorial I put a CheckBox in header, on its check change, all the checkboxes in the list check change and if you change the check on any of checkboxes in the list the header check also change automatically.

Using the code 

I have created a Class Employee, add some records to it and bind it to grid. 

C#
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Designation { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
    var employees = new List<Employee>()
    {
        new Employee(){ Id = 1, Name = "Ms. Nancy Davolio",     Address = "507 - 20th Ave. E.  Apt. 2A",    Designation = "Sales Representative"},
        new Employee(){ Id = 2, Name = "Dr. Andrew Fuller",     Address = "908 W. Capital Way",             Designation = "Vice President Sales"},
        new Employee(){ Id = 3, Name = "Ms. Janet Leverling",   Address = "722 Moss Bay Blvd.",             Designation = "Sales Representative"},
        new Employee(){ Id = 4,	Name = "Mrs. Margaret Peacock", Address = "4110 Old Redmond Rd.",           Designation = "Sales Representative"},
        new Employee(){ Id = 5,	Name = "Mr. Steven Buchanan",   Address = "14 Garrett Hill",                Designation = "Sales Manager"},
        new Employee(){ Id = 6,	Name = "Mr. Michael Suyama",    Address = "Coventry House  Miner Rd.",      Designation = "Sales Representative"},
        new Employee(){ Id = 7,	Name = "Mr. Robert King",       Address = "Edgeham Hollow  Winchester Way", Designation = "Sales Representative"},
        new Employee(){ Id = 8,	Name = "Ms. Laura Callahan",    Address = "4726 - 11th Ave. N.E.",          Designation = "Inside Sales Coordinator"},
        new Employee(){ Id = 9, Name = "Ms. Anne Dodsworth",    Address = "7 Houndstooth Rd.",              Designation = "Sales Representative"}
    };

    gvEmployees.DataSource = employees;
    gvEmployees.DataBind();
}

This is my Grid Control 

C#
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333"
    GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox runat="server" ID="chkAll" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="chkEmployee" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblID" Text='<%#Eval("Id") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblName" Text='<%#Eval("Name") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblAddress" Text='<%#Eval("Address") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Designation">
            <ItemTemplate>
                <asp:Label runat="server" ID="lblDesignation" Text='<%#Eval("Designation") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <EditRowStyle BackColor="#7C6F57" />
    <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#E3EAEB" />
    <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F8FAFA" />
    <SortedAscendingHeaderStyle BackColor="#246B61" />
    <SortedDescendingCellStyle BackColor="#D4DFE1" />
    <SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView> 

We have two requirements.

1. When top CheckBox checked/unchecked, we have to check/uncheck all the CheckBoxes in the list.

Following function fulfill the requirement. 

$("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
    //Check/uncheck all checkboxes in list according to main checkbox 
    $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', $(this).is(':checked'));
});


2. On each of the list CheckBox checked/unchecked, we have to determine Check/Uncheck top CheckBox.     

$("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").click(function() {
    //Get number of checkboxes in list either checked or not checked
    var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
    //Get number of checked checkboxes in list
    var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
    //Check / Uncheck top checkbox if all the checked boxes in list are checked
    $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
});    

Following is Complete Javascript. 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").click(function() {
            //Get number of checkboxes in list either checked or not checked
            var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
            //Get number of checked checkboxes in list
            var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();
            //Check / Uncheck top checkbox if all the checked boxes in list are checked
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
        });

        $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            //Check/uncheck all checkboxes in list according to main checkbox 
            $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', $(this).is(':checked'));
        });
    });
</script>

  Image 1 

Thanks and regards.   

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Answercheck uncheck gridview checkboxes using jquery Pin
varaprasadreddy.bh23-Sep-12 8:26
varaprasadreddy.bh23-Sep-12 8:26 
GeneralMy vote of 1 Pin
Vitaly Tomilov6-Sep-12 12:26
Vitaly Tomilov6-Sep-12 12:26 
Question[My vote of 1] this is just too awful PinPopular
Seishin#17-Jul-12 4:43
Seishin#17-Jul-12 4:43 
AnswerRe: [My vote of 1] this is just too awful Pin
Nasser Malik17-Jul-12 5:18
Nasser Malik17-Jul-12 5:18 
GeneralRe: [My vote of 1] this is just too awful Pin
Vitaly Tomilov6-Sep-12 12:23
Vitaly Tomilov6-Sep-12 12:23 
You do not need to complicate the code to stick to the grid-only selectors. This is just so trivial, but boy you messed this one up! Smile | :)
Let's agree to disagree!
Boris the animal Just Boris.

AnswerRe: [My vote of 1] this is just too awful Pin
dotnetpickles12-Feb-14 0:58
dotnetpickles12-Feb-14 0:58 
GeneralRe: [My vote of 1] this is just too awful Pin
Nasser Malik14-Feb-14 7:30
Nasser Malik14-Feb-14 7:30 

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.