In ASP.NET, the style of GridView is usually controlled either by using a CSS file or by using a skin file and in many cases this works well, but what if we need to style the GridView as follows:
Of course it can be done in code behind by looping through the GridView rows and applying different CSS class for each row. It needs at least a “For” loop and a calculation of the reminder of (Total Row Count divided by Row Number), besides, it is not a smart idea to apply complex styles in code behind and it should be avoided as much as possible, because it brings in maintainability issues. If, for instance, later on the style of the GridView needs to be changed again, then we will have to modify the code behind file, rebuild the application (if it is a web application), and redeploy it.
However, believe or not, with the powerful jQuery, the above style can be accomplished with only five lines of code in the <head> section of the page, and no code behind coding is needed at all.
Here is the jQuery script for styling the above GridView:
The GridView is defined as follows:
The GridView is rendered as an HTML table element with id=”ctl00_Content_gvCustomerList” or something similar, and each GridView row is rendered as <tr>, each GridView cell is rendered as <td>, and GridView’s header row is rendered as <th>. Bear this mind, now let’s take a deep look at the jQuery code:
First of all, the dollar sign “$” is the standard jQuery function call, you can replace it with “jQuery” if you wish. The above function call means: find a “table” element whose “id” ends with (“$=”) “gvCustomerList”, once find it, add a class (“addClass”) called “grid” to the table element.
Not that bad, right? Now let’s take a look at the second line of the jQuery code:
The first part is the same as above, the second part “th” means to find all “<th>” elements with the table element. So the complete meaning of the function call is: find all “<th>” elements within a table element whose id ends with “gvCustomerList”, then add a class called “grid-header” to all matching <th> elements.
So far so good. Now take a look at the third line:
This one looks very complicated, but fear not, it is actually not as intimidating as it seems to be. First, let me explain what “:nth-child(3n+1)” means. It means “the item after every 3rd element”. So “tr:nth-child(3n+1)” means to “return the <tr> element after every third <tr> element”. Now it should be clear about the meaning of the above function call: return the <tr> element after every third <tr> element within the <tbody> element of a table element whose id ends with “gvCustomerList”, then add a class called “grid-alternating-item-one” to the returned element.
Once you understand the meaning of this line, you should be able to understand the rest lines of code.
From this example, we can see that jQuery is very powerful and can accomplish very complex tasks with very few lines of code.
As usual, there is a live demo of this example.