How to select/deselect all checkbox in gridview using jquery

aspdotnetcodebook In this post I will show how to select/deselect checkbox present inside gridview using jquery.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewSelectAll.aspx.cs"
    Inherits="GridViewSelectAll" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#<%=gvProducts.ClientID%> input[id$='chkAll']:checkbox").click(function () {
                $("#<%=gvProducts.ClientID%> input[id*='chkSelected']:checkbox").attr('checked', $(this).is(':checked'));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        <input type="checkbox" id="chkAll" runat="server" value='<%#Eval("ProductID") %>' />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <input type="checkbox" id="chkSelected" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GridViewSelectAll : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        gvProducts.DataSource = ProductDAL.GetProducts();
        gvProducts.DataBind();
    }
}
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
}
public class ProductDAL
{
    public static List<Product> GetProducts()
    {
        return new List<Product>()
                   {
                       new Product() {ProductID = 1, ProductName = "P001", Description = "Desc01"},
                       new Product() {ProductID = 2, ProductName = "P002", Description = "Desc02"},
                       new Product() {ProductID = 3, ProductName = "P003", Description = "Desc03"},
                       new Product() {ProductID = 4, ProductName = "P004", Description = "Desc04"},
                       new Product() {ProductID = 5, ProductName = "P005", Description = "Desc05"},
                   };
    }

}

No comments:

Post a Comment