Saturday, 22 July 2017

Check uncheck or select deselect CheckBox using jQuery with GridView in ASP.NET

In this article, I am going to explain you, how to check and uncheck all checkboxes using jQuery in asp.net gridview. If header row checkbox is checked then all row checboxes should be checked and if any of row checkbox is unchecked then header checkbox should be unchecked.

DOWNLOAD SOURCE CODE
check uncheck or select deselect all checkboxes using jQuery
check uncheck or selectde select all checkboxes using jQuery in gridview

Data Source

To bind gridview, we need to have some dummy data. Below is the script to create table and insert data into it. Script is attached inside download source code folder.

create table tblStudent
(
Id int primary key identity,
Name varchar(50),
Gender varchar(10),
Marks int,
City varchar(50)
)
go
insert into tblStudent values('Rahul', 'Male', 10, 'Mumbai')
insert into tblStudent values('John','Male', 15,'London')
insert into tblStudent values('Mathew','Male', 20,'Sydney')
insert into tblStudent values('Mary','Female', 25,'Delhi')
insert into tblStudent values('Mithum','Male', 30,'Delhi')
insert into tblStudent values('Sara','Female', 35,'London')
insert into tblStudent values('Rahul','Male', 40,'Mumbai')
insert into tblStudent values('John','Male', 45,'London')
insert into tblStudent values('Mathew','Male', 50,'Sydney')
insert into tblStudent values('Mary','Female', 55,'Delhi')
insert into tblStudent values('Mithum','Male', 60,'Delhi')
insert into tblStudent values('Sara','Female', 65,'London')
insert into tblStudent values('Rahul','Male', 70,'Mumbai')
insert into tblStudent values('John','Male', 75,'London')
insert into tblStudent values('Mathew','Male', 80,'Sydney')
insert into tblStudent values('Mary','Female', 85,'Delhi')
insert into tblStudent values('Mithum','Male', 90,'Delhi')

Design GridView

In aspx file, create a gridview control as shown below. In the first TemplateField, there are two check-boxes chkHead and chkRow.

<div style="margin-top: 25px; margin-left: 250px;">
    <asp:GridView ID="grdStudent" runat="server" DataKeyNames="Id" CellPadding="5" 
       AutoGenerateColumns="false" Width="540px" OnPageIndexChanging="grdStudent_PageIndexChanged" 
       AllowPaging="true" PageSize="5">
        <AlternatingRowStyle BackColor="White" />
        <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
        <RowStyle HorizontalAlign="Center" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Left" />
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkHead" runat="server"></asp:CheckBox>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkRow" runat="server"></asp:CheckBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblName" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Gender">
                <ItemTemplate>
                    <asp:Label ID="lblGender" runat="server" Text='<%#Eval("Gender") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Marks">
                <ItemTemplate>
                    <asp:Label ID="lblMarks" runat="server" Text='<%#Eval("Marks") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="City">
                <ItemTemplate>
                    <asp:Label ID="lblCity" runat="server" Text='<%#Eval("City") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Code-Behind File

In code-behind file, bind gridview control using dummy data from database as shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;//namespace added
using System.Configuration;//namespace added
using System.Data.SqlClient;//namespace added

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string ConnString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }

        private void BindGrid()
        {
            DataSet ds = null;
            SqlConnection con = null;
            try
            {
                con = new SqlConnection(ConnString);
                SqlCommand cmd = new SqlCommand("select * from tblStudent", con);
                cmd.CommandType = CommandType.Text;
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                ds = new DataSet();
                sda.Fill(ds);

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    grdStudent.DataSource = ds.Tables[0];
                    grdStudent.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    grdStudent.DataSource = ds;
                    grdStudent.DataBind();
                    grdStudent.Rows[0].Visible = false;
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
            }
        }

        protected void grdStudent_PageIndexChanged(object sender, GridViewPageEventArgs e)
        {
            grdStudent.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
}

jQuery Code

First we need to add jQuery file to our application. We can either download latest jQuery file from http://jquery.com/download/ and put jQuery file into Script folder of our application or we can directly use CDN links in code as shown below.
Code to load jQuery Framework from Google CDN

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Code to load jQuery Framework from Microsoft CDN
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js">
</script>
Code to load jQuery Framework from jQuery Site(EdgeCast CDN)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>

I am using downloaded jQuery file as shown below and below is the complete jQuery code to select and deselect check-boxes.

<head runat="server">
  <title></title>
  <script src="Scripts/jquery-3.0.0.js" type="text/javascript"></script>
  
  <script type="text/javascript" language="javascript">
    $(document).ready(function () {

      //this code will be executed on click of header row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").click(function () {

        //check if header row checkbox is checked and store into variable
        var flag = $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").is(':checked');

        //find all row checkboxes: if flag == true then set attribute checked=true or if flag == false then set checked=false
        $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").prop('checked', flag);

      });

      //this code will be executed on click of data row checkbox
      $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").click(function () {

        //count total number of row checkboxes
        var rowCheckboxesCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox").length;

        //count total number of row checkboxes which are checked
        var rowCheckboxesCheckedCount = $("#<%=grdStudent.ClientID%> input[id*='chkRow']:checkbox:checked").length;

        // if counts are same that means:  total number of row checkboxes == total number of row checkboxes which are checked
        // then find header row checkbox and set to true or false
        $("#<%=grdStudent.ClientID%> input[id*='chkHead']:checkbox").prop('checked', rowCheckboxesCount == rowCheckboxesCheckedCount);

      });

    });
  </script>
</head>
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON