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

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...

Utilizing AngularJS to Retrieve URL Parameters Within a Controller

I am attempting to retrieve URL parameters in my controller: Although I came across this example, I encountered an error that appears to be connected to the loading of necessary modules. app.controller('WidgetCtrl', ['$scope', '$ ...

What is the process for updating JSON using TextFields?

I am currently facing an issue with my TextFields displayed within a material-ui dialog. These TextFields are initially populated by JSON data, which you can see in the example below. The problem is that once the TextFields are populated, I am unable to up ...

Is it possible for XSS attacks to exploit the HREF attribute when used with jQuery?

Burp suite displaying an error message. The application seems to have a potential vulnerability related to DOM-based cross-site scripting. Data is retrieved from the location and passed to jQuery() using the following statement: jQuery(location). ...

Getting the value of a radio button in an array list using Ajax

I have a form with multiple radio lists set up like this: <div id="Question[180]"> <input name="Question[180]" id="6" value="6" class="inputbox" size="1" type="radio">yes <input name="Question[180]" id="7" value="7" class="inputbox" ...

Express.js Res redirection problem occurring with Backbone.js due to failure in redirecting hashtag URLs

Issue Summary: Having trouble with Express.js redirect functionality. The problem occurs when trying to redirect after entering /#impulse, but works fine with /impulse/. Server processes the request for /#impulse before applying redirect checks, which re ...

Ways to transfer information from a function within one element to another element

I have two components: one that logs the indexes of a carousel and I need to pass these indexes into the second component. First Component <template> <div class="container container--white"> <Header /> <carousel-3d @a ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Navigating with Link in React Router DOM v5 to successfully pass and catch data

In the process of developing a basic chat application, I encountered an issue with passing the username via the Link component. Below is the relevant code snippet: <Link to={{ pathname: `/${room}`, state: { the: user } }}> Enter room </Link> ...

How can I send a value to an Angular element web component by clicking a button with JavaScript?

I want to update the value of an input in an Angular component by clicking on a button that is outside of the Angular Element. How can I achieve this in order to display the updated value in the UI? Sample HTML Code: <second-hello test="First Value"&g ...

Choosing several buttons in typescript is a skill that every programmer must possess

I need help with selecting multiple buttons in TypeScript. The code I tried doesn't seem to be working, so how can I achieve this? var input = document.getElementById('input'); var result = document.getElementById('result'); v ...

Is there a way to send a promise resolve or reject from a function code within router.post() in Express?

Below is my code in express (node.js) router.post('/example.json', function (req, res) { // getFileInfo is a function to return an array return getFileInfo(req.body.fileList).then((array) => { axios({ method: 'post', ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Table header containing the weekdays for a jQuery calendar display

I need some assistance in creating a basic monthly calendar using a table. Check out this demo: www.jsfiddle.net/pzdw0s2n/1/ ...

Ensure that the placeholder remains visible as you type in the input field

Is there a way to implement an input text field in React with the placeholder "DD-MM-YYYY," that partially disappears as I start typing? For example, when I type "02-," only "-MM-YYYY" should remain visible as part of the placeholder. ...

State calculation occurs too tardily

I'm working on creating a simple like button that changes color based on whether it's liked or not. I've tried to calculate this beforehand using React.useEffect, but it seems to be calculating afterwards instead... The hearts are initially ...

Guide on Sending a POST Request via HTTPS in Websites

I am developing a browser extension for Chrome that requires sending a post request to a server using standard HTTP. However, this is causing a mixed content error when I'm on a website that uses HTTPS, and the browser refuses to process my request. ...

Launch the desired div in a fancybox from a separate webpage

i have a table with links to another html doc like this <div id="gallery_box"> <ul> <li> <a href="http://www.geestkracht.com" target="_blank"><img src="images/gallery/Geestkracht.jpg" alt="G ...

Issues with looping Jquery ajax请求

Is there a bug in the code? Here are some examples: for(i=0;i<2;i++){ $.ajax({ url : 'process.php', type: "POST", data : "abcd", success : function(data){ alert(i); } }) } or for(i=0;i<2;i++){ $.post("proc ...

``There seems to be a Flask error occurring following a redirect from the POST

In my current project, I am utilizing a combination of Flask and Javascript. When the user provides input on a web page, I send a JSON object back to the Flask server in the following manner: var xhr = new XMLHttpRequest(); xhr.open('POST', &apo ...