Aug 29, 2012

Check all Checkbox in Gridview using JQuery

Selecting all checkboxes by selecting the checkbox in the header of the gridview is a common operation in ASP.NET applications.

We could do the same thing with javascript but with JQuery same can de done with writing less code and less effort.

Markup code (Gridview1.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView1.aspx.cs" Inherits="GridView1" %>
<html>
<head runat="server">
    <title></title>
    <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 () {
            $("#<%=grid.ClientID%> input[id*='chkAll']:checkbox").click(function () {
                if ($(this).is(':checked'))
                    $("#<%=grid.ClientID%> input[id*='chkSelect']:checkbox").attr('checked', true);
                else
                    $("#<%=grid.ClientID%> input[id*='chkSelect']:checkbox").attr('checked', false);
            });

            $("#<%=grid.ClientID%> input[id*='chkSelect']:checkbox").click(CheckUncheckAll);
        });

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

            if (totalCheckboxes == checkedCheckboxes) {
                $("#<%=grid.ClientID%> input[id*='chkAll']:checkbox").attr('checked', true);
            }
            else {
                $("#<%=grid.ClientID%> input[id*='chkAll']:checkbox").attr('checked', false);
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grid" runat="server" AutoGenerateColumns="False" DataKeyNames="EmpId,EmpName"
            CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <asp:CheckBox runat="server" ID="chkAll" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox runat="server" ID="chkSelect" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="EmpId" HeaderText="Employee ID" ItemStyle-Width="100px" ItemStyle-Wrap="true">
                    <ItemStyle Wrap="True" Width="100px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="EmpName" HeaderText="Name" ItemStyle-Width="100px" ItemStyle-Wrap="true">
                    <ItemStyle Wrap="True" Width="100px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="Gender" HeaderText="Gender" ItemStyle-Width="100px" ItemStyle-Wrap="true">
                    <ItemStyle Wrap="True" Width="100px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField DataField="DOJ" HeaderText="Date of Joining" ItemStyle-Width="100px"
                    ItemStyle-Wrap="true">
                    <ItemStyle Wrap="True" Width="100px"></ItemStyle>
                </asp:BoundField>
            </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Code Behind (Gridview1.aspx.cs code)
using System;
using System.Collections.Generic;
public partial class GridView1 : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindGrid();
    }

    private void BindGrid()
    {
        List<Emp> EmpList = new List<Emp>();
        EmpList.Add(new Emp { EmpID = "EMP001", EmpName = "Sandeep Mittal", Gender = "Male", DOJ = "01/01/2011" });
        EmpList.Add(new Emp { EmpID = "EMP002", EmpName = "Ritesh Kumar", Gender = "Male", DOJ = "05/01/2011" });
        EmpList.Add(new Emp { EmpID = "EMP003", EmpName = "Abhay Kumar", Gender = "Male", DOJ = "05/03/2011" });
        grid.DataSource = EmpList;
        grid.DataBind();
    }  
}

public class Emp
{
    public Emp()
    {       
    }

    private string _EmpId;
    private string _EmpName;
    private string _Gender;
    private string _DOJ;
    public string EmpID { get { return _EmpId; } set { _EmpId = value; } }
    public string EmpName { get { return _EmpName; } set { _EmpName = value; } }
    public string Gender { get { return _Gender; } set { _Gender = value; } }
    public string DOJ { get { return _DOJ; } set { _DOJ = value; } }     
}