Menus

Monday, April 15, 2013

Using jQuery with CheckBox and ASP.NET GridView

In this article, we will create an ASP.NET GridView which contains a Checkbox column. We will then access all the checked rows of the GridView and calculate the Sum of the values of a column and display it to the user. Sounds fun? Let’s get started!

Open Visual Studio 2010 > Create an ASP.NET site. In the code behind of the Default.aspx page, add the following class which represents a hosting plan:
Now add a GridView control to the aspx page as shown below:
Let us now bind this GridView with the custom Hosting class we created above:
Your GridView should look similar to the following:
All set! It’s time for some jQuery magic now. What we will do is calculate the sum of the ‘AddOn Cost’ column for only those rows that are checked. Use the following jQuery code:
Let us understand this code step by step:
When a checkbox is clicked, we invoke a function called calculateSum() and pass in the column index 4. Note that column numbering starts at one, not at zero. Hence the 4th column index in our example is ‘AddOn Cost’
We then use a selector as shown below, to get only those rows which are checked and return a single column with the specified numeric index, in our case 4. Using the nth-child with the index lets me iterate through each cell using children(). You may also add the GridView ID or the cssclass to the selector if you have more than one GridView’s on the page.
$("tr:has(:checkbox:checked) td:nth-child(" + colidx + ")")
The entire calculateSum() function looks as shown below:
Once we have our selector, we use .each() to iterate over this jQuery object and add the column value to the ‘total’ variable. The parseFloat( ) parses strings into numbers.
The output is as shown below:
Note: If you are using the GridView with paging, then handling the sum of all checkboxes across all pages can be tricky. You will have to use ViewState and track all the rowID's and the column values in an array or something similar.

No comments:

Post a Comment