Calculating GridView Fields Using jquery

Using jquery library with ASP Controls can be a good practice to handle any client script. Furthermore, using jquery with GridView would be more efficient than using native JavaScript. JavaScript needs a lot of codes, on the other hand, Jquery helps to build robust program with less codes and work.

In this article, I will illustrate how to calculate GridView Fields by jquery. In the following example, the price and the quantity of each item are calculated in every separate row, and the gross price is given at the end.



<html xmlns="">
<head runat="server">
  <script type="text/javascript" src=""></script>
  <script type="text/javascript">
    $(document).ready(function () {
      $("[id*=GridView1]input[type=text][id*=txtCalc]").keyup(function (e) {
        var price = $(this).closest('tr').find("input[type=text][id*=txtCalcPrice]").val();
        var quantity = $('tr').find("input[type=text][id*=txtCalcQuantity]").val();
        var total = parseInt(price) * parseInt(quantity);
    var gross;
    function GrossTotal() {
      gross = 0;
      $("[id*=GridView1][id*=lblTotal]").each(function (index, item) {
        gross = gross + parseInt($(item).text());
  <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
        <asp:TemplateField HeaderText="ItemName">
            <asp:Label ID="lblItemName" runat="server" Text='<%#Eval("ItemName")%>'></asp:Label>
        <asp:TemplateField HeaderText="Price">
            <asp:TextBox ID="txtCalcPrice" runat="server" Text='<%#Eval("Price")%>' />
        <asp:TemplateField HeaderText="Quantity">
            <asp:TextBox ID="txtCalcQuantity" runat="server" Text='<%#Eval("Quantity")%>' />
        <asp:TemplateField HeaderText="Total">
            <asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label>
            <asp:Label ID="lblGrossTotal" runat="server" Text="0"></asp:Label>


The code behind:


public partial class CalculateGridView : System.Web.UI.Page
  protected void Page_Load(object sender, EventArgs e)
    var items = new List<Item>
              new Item("Item1", 0, 0),
              new Item("Item2", 0, 0),
              new Item("Item3", 0, 0),
              new Item("Item4", 0, 0)
    GridView1.DataSource = items;
public class Item
  public string ItemName { get; set; }
  public int Price { get; set; }
  public int Quantity { get; set; }
  public Item(string itemName,int price,int quantity)
    ItemName = itemName;
    Price = price;
    Quantity = quantity;


In addition, you need to check that the user enters only positive numbers. To do so, you can use jquery- numeric plugin. This plugin helps you to restrict the user from entering an incorrect format .

Hope that help.


Download Source Code


Comments have been disabled for this content.