JQuery Select Header Checkbox When All Child Checkboxes Selected in Asp.net Gridview

7:22:00 am 0 Comments

Introduction:


In this article I will explain how to check/uncheck or select/deselect all the checkboxes in gridview with header checkbox using JQuery in asp.net.

Description:

 
Now I will explain how to select/deselect header checkbox when all child checkboxes selected in gridvuew using JQuery.
For that first design your aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>check uncheck all checkboxes in gridview using jquery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('[id$=chkHeader]').click(function() {
$("[id$=chkChild]").attr('checked', this.checked);
});
$("[id$=chkChild]").click(function() {
if ($('[id$=chkChild]').length == $('[id$=chkChild]:checked').length)
{
$('[id$=chkHeader]').attr("checked", "checked");
}
else{
$('[id$=chkHeader]').removeAttr("checked");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserInfo" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkChild"  runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Now add following namespaces in codebehind
C# Code
using System;
using System.Data;
using System.Data.SqlClient;

After that add following code in code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=ARYAN-PC\SQLEXPRESS;Integrated Security=true;Initial Catalog=SalmanTempDB");
con.Open();
SqlCommand cmd = new SqlCommand("select TOP 10 UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code
Imports System.Data
Imports System.Data.SqlClient
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
' This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=ARYAN-PC\SQLEXPRESS;Integrated Security=true;Initial Catalog=SalmanTempDB")
con.Open()
Dim cmd As New SqlCommand("select TOP 10 UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub
End Class


0 comments: