Calculating the sum of values in a GridView using ASP.NET

I have an ASP.NET Web Application where I am utilizing a BulkEditGridView to create an order form. This GridView allows users to edit all rows simultaneously. Within the grid, there is a column that calculates the total cost for each item (cost x quantity), as well as a grand total field at the bottom of the page. Currently, these fields only update on every post-back. I am looking for a way to dynamically update these fields so that when users modify quantities, the totals and grand total reflect the changes in real-time. I have tried using AJAX solutions for this task, but the asynchronous post-backs cause issues with the user experience on the page. I believe that there must be a client-side solution available, and I am hopeful that someone from the community can provide some insights.

Answer №1

One way to replicate your calculations in JavaScript is by utilizing jQuery to retrieve all the items. Here is a simple method to accomplish this:

$("#myGridView input[type='text']").each(function(){
  this.change(function(){
    updateTotal(this.value);
  });
});

If your calculations prove too intricate for JavaScript or time constraints limit you, consider making an AJAX call to a web service. Suppose we have a web service structured like this:

[WebMethod, ScriptMethod]
public int UpdateTotal(int currTotal, int changedValue){
  // perform necessary actions and return
}

To invoke the web service, you will need to incorporate some JavaScript code using either jQuery or MS AJAX. Below is an example combining both methods:

$("#myGridView input[type='text']").each(function(){
  this.change(function(){
    Sys.Net.WebServiceProxy.invoke(
      "/Helpers.asmx",
      "UpdateTotal",
      false,
      { currTotal: $get('totalField').innerHTML, changedValue: this.value },
      showNewTotal
    );
  });
});

function showNewTotal(res){
  $get('totalField').innerHTML = res;
}

For more information on the Sys.Net.WebServiceProxy.invoke method, visit this link: http://www.asp.net/AJAX/Documentation/Live/ClientReference/Sys.Net/WebServiceProxyClass/WebServiceProxyInvokeMethod.aspx

Answer №2

If you want to keep updating totals in your RowDataBound method as textboxes change, one solution is to create some JavaScript logic for this purpose.

During the RowDataBound event, start constructing a JavaScript string that will calculate the values of the textboxes you want to add together. The beauty of RowDataBound is that you can easily access the Client Side ids of these textboxes by using TextBox.ClientId. Include this JavaScript code on the page and also attach an onkeyup event to each relevant textbox to trigger this script.

For example, within a GridView's RowDataBound event:

private string _jscript;
protected void gridview_RowDataBound(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.DataRow)
   {
      //Grab the target textbox
      Textbox tb = e.Row.FindControl("tbAddUp");
      //Assign the function to be called on this textbox's attribute
      tb.Attributes.Add("onkeyup", "MyAddUpJavaScriptMethod();");
      //Construct the necessary JavaScript for MyAddUpJavaScriptMethod
      jscript += "document.getElementById('" + tb.ClientId + '").value + ";
   }
}

After creating the complete script, utilize the Page.ClientScript class to add a method to your page that will be triggered by the onkeyup event in your textboxes, named "MyAddUpJavaScriptMethod".

I hope this explanation aids in understanding the process and proves helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Asynchronous Values in a Different JavaScript Function

Currently delving into the world of destructuring arrays in Javascript, I find myself faced with the challenge of accessing these variables in other functions. I attempted to retrieve the array by calling a function and then using console.log(thermostatAr ...

AngularJs Number Formatting: A Step-By-Step Guide

Is there a way to format a number from 10000 to 10,000.00 using only HTML and the ng-Model directive, without involving the controller file? I attempted to achieve this in the controller file through logic, but it always returns the number in the "10,00 ...

Passing a particular object from an array of objects as props in React Native

Suppose you have a static array consisting of 4 objects and the goal is to pass specific data items from the third object in this array. How can this task be accomplished? Let's consider an example: const ENTRIES = [ { name: "John" color: "#fffff" f ...

"Dynamically moving" background on canvas

Struggling to animate a dynamic "background" for my canvas project using raphaelJS. Here's the code snippet I'm working with: function bg(){ h = 0; var terra = paper.rect(0, 500 + h, 900, 100); terra.attr({'fill': '# ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Is it possible to trigger a function dynamically upon checking a checkbox?

I’ve been working on a simple string formatting app using React, diving into hooks as I go. Right now, I’m tackling the part where I need to trigger specific text formatting functions based on checkbox selections. Let's say, if the lowercase chec ...

When working on a React/Redux application, how do you decide between explicitly passing down a prop or retrieving it from the global state using mapStateToProps?

As I embark on creating my inaugural React-Redux application, a recurring decision I face is whether to employ <PaginationBox perPage={perPage} /> or opt for <PaginationBox /> and then implement the following logic: function mapStateToProps({p ...

Tips for effectively binding attributes based on conditions in Vue.js

Is it possible to conditionally bind attributes in Vue? Yes, you can achieve this using the v-bind directive: Here is an example: <img :src=" status = true ? 'open.svg' : 'close.svg'"> In Angular, this functionality i ...

Vue.js - Capturing a scroll event within a vuetify v-dialog component

Currently, I am working on a JavaScript project that involves implementing a 'scroll-to-top' button within a Vuetify v-dialog component. The button should only appear after the user has scrolled down by 20px along the y-axis. Within the v-dialog, ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

Scripting in jQuery to create dropdown menus

I've encountered a unique issue on my website where a user's selection from one list should update the values in another list: <form id="form1"> <div> <select id="workField"> <option value ...

I am interested in retrieving an array

Here is the array I am working with { Colors: 'Blues', Department: 'Clearance', Size: [ 'Runners', 'Custom Sizes' ], Shape: 'Round', Designer: 'B. Smit', } The desired output should be ...

Changing the MIME type of a JavaScript file in a Jade/Pug environment to text/html

Hi there, I've been experimenting with jade/pug to get my node.js backend to render the front-end pages. However, I'm facing some issues when trying to include JavaScript for certain functionalities. Whenever I try to load it, I encounter this er ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Ways to retrieve the upcoming possible date

I'm currently working on a project using express and I need to implement a scheduling calendar. My goal is to provide users with the next available day in the format YYYY-MM-DD. Here are the rules for determining the next available day: The default ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

Why is the promise not returning an integer value, but instead returning undefined?

My validation process includes checking the integrity of the down streaming data to the server and verifying its existence in the database. The code snippet from model.js: const mongoose = require('mongoose'); const User = new mongoose.Schema({ ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

The browser is not displaying the results from Mongodb, yet they are appearing in the console

I am currently using the following code for my router: let mongoose = require('mongoose'); // connecting with our model let ByProduct = require('../models/Byproduct') router.get('/',(req,res,next)=>{ ByProduct.find().th ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...