Click here to Skip to main content
15,885,278 members
Articles / Check

Check all checkboxes in GridView By jQuery

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
28 Jul 2012CPOL 6.6K  
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

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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.

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

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

<asp:GridView ID="gvEmployees" runat="server" 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 () {
    if ($(this).is(':checked'))
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
    else
        $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
});

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

function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }

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(CheckUncheckAllCheckBoxAsNeeded);
        $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            if ($(this).is(':checked'))
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', true);
            else
                $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").attr('checked', false);
        });
    });

    function CheckUncheckAllCheckBoxAsNeeded() {
        var totalCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox").size();
        var checkedCheckboxes = $("#<%=gvEmployees.ClientID%> input[id*='chkEmployee']:checkbox:checked").size();

        if (totalCheckboxes == checkedCheckboxes) {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
        }
        else {
            $("#<%=gvEmployees.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
        }
    }
</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
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --