Change Background Color of GridView Cell using jQuery

Users often ask how to change the background color of an ASP.NET GridView cell, if the cell matches a condition. It’s actually quite simple using jQuery. Just use this code in the <head> section of your page:

<head runat="server">
<
title>GridView Cell Background Color by DevCurry.com</title>
<
style type="text/css">
.grdCell
{
background-color:Gray;
}
</style>

<
script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</
script>

<
script type='text/javascript'>
$(function () {
$("#grdCust td").filter(function () {
return $(this).text() == "France";
}).addClass("grdCell");
});
</script>
</
head>

Here we are using the jQuery filter() method that reduces the set of matched elements to those that match the selector or pass the function's test. In our case, we are sending the filter() method an anonymous function that can be used to filter the table cells that have the value ‘France’ in them. The $(this) within the function refers to each DOM element in the wrapper set.

As you would expect, only the cells containing the values ‘France’ get highlighted.

image

If you are doing jQuery development with ASP.NET Controls, you will find my eBook helpful 51 Recipes with jQuery and ASP.NET Controls



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Andrey said...

Nice aspnet gridview tips.