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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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.