Sunday, 25 August 2013

Highlight Gridview Row When CheckBox is Checked in ASP.NET using JQuery


This example will how  we can highlight gridview row when checkbox is checked using JQuery.

ASPX PAGE

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Highlight row when checkbox is checked in gridview asp.net</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() {
// Header Checkbox click function
$('[id$=chkHeader]').click(function() {
if ($('[id$=chkHeader]:checked').length>0) {
$('[id$=chkChild]').parent().parent().addClass('highlightRow');
}
else {
$('[id$=chkChild]').parent().parent().removeClass('highlightRow');
}
$("[id$=chkChild]").attr('checked', this.checked);
});
// Child Checkbox click function
$("[id$=chkChild]").click(function() {
if(this.checked) {
$(this).parent().parent().addClass('highlightRow');
}
else {
$(this).parent().parent().removeClass('highlightRow');
}
if ($('[id$=chkChild]').length == $('[id$=chkChild]:checked').length) {
$('[id$=chkHeader]').attr("checked", "checked");
}
else {
$('[id$=chkHeader]').removeAttr("checked");
}
});
});
</script>
<style type="text/css">
.highlightRow
{
background-color:Red;
Color:White;
}
</style>
</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>

C# PAGE

using System;
using System.Data;
using System.Data.SqlClient;
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=PERSONAL\SQLEXPRESS;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select FirstName,LastName,City from UserInfo", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}