Solved

Running Total on ASP.Net webform with web form text boxes...

Posted on 2004-04-09
28
771 Views
Last Modified: 2012-06-21
I currently collect several pieces of data on a webform.

I would like to show the sum of the textboxes as the user is entering them on the form.

What is the best way to do this?  Would you have a sample of this working?


Thanks,

Rog
0
Comment
Question by:Rog
  • 13
  • 8
  • 3
  • +2
28 Comments
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
handle the onChange event of these textboxes with javascript ... then make the javascript print the totals on the page ...

an example can be seen viewing source on this page .. http://www.mcfedries.com/JavaScript/OrderTotals.asp

Greg
0
 
LVL 28

Expert Comment

by:iboutchkine
Comment Utility
Create a label and
Label1.Text = Ctype(txt1.Text.ToDouble + txt2.Text.ToDouble + etc)
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Greg,

I looked at the sample, it utilized HTML Input not Web From Textboxes.  I am using the web form text boxes for input to a SQL statement when a submit command button is pressed in the ASP.Net code.

So I am looking for something that will work with web form text boxes..

 iboutchkine...

This would require a trip back and forth to the server.  I want to do this on the server side...

Rog
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
you want this to happen on the server ?!?!

if you want it to happen on the server just register a postback event on them.

"This would require a trip back and forth to the server.  I want to do this on the server side..."

then why are you complaining that his answer requires a roundtrip ? of course its going to require a round trip.

using the example I gave with web form controls is very simple ... javascript still supports the "this" object which you can pass to a function i.e. when you register the event on the control.
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
grr I keep doing that by accident ... I was going to say that you dont have to since you could just total them all up instead of trying to save a few addition operations by adjustng your previous total ...
0
 
LVL 28

Expert Comment

by:mmarinov
Comment Utility
you can set AutoPostBack property of each textbox control to true - this will cause postback when you leave the control
add a label control on your form and create onchange event for the textboxes.
in this event you can write
c#
private void txtBox_TextChanged(object sender, System.EventArgs e)
{
  TextBox tb = (TextBox)sender;
   Label1.Text = int.Parse(Label1.Text) + int.Parse(tb.Text);
}

HTH
B..M
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
B..M given that this is simply adding up textboxes why would you force a postback ? Doing it in javascript would piss off the user alot less :)
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
also you state that the example is using html textboxes ... go to your page and right click then view source ... the webforms textboxes are creating html text boxes they are identical when iewed from the client's side ... only the server side knows the difference.
0
 
LVL 28

Expert Comment

by:mmarinov
Comment Utility
gregoryyoung:
1. I force postback because every time the user enter value in one of the textbxes the total sum will be changed!
2. I don't use javascript because it is more work to do the javascript work on every browser instead of making thinkgs easy - of course if the page contains a lot of information i won't use autopostback=true and will calculate the total sum when the page is submitted at the end
3. I don't use HTML textboxes but i use TextBox Web Contols - and the reaseon of this is said in 1.!

B..M
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
Yes thank you I understand the total will be changed hence why I posted a link to javascript doing such a thing ...

html textboxes and text box web controls are the same thing once viewed in a browser thus javascript sees them in the same way ! ... Go look what your web controls generate for html ! You can get the generated name of a web control quite easily in your code behind as well (even though you do not need it for this example). Exactly how do you think the web controls are generating your wasteful postbacks its being done through javascript ...

posting back for such a trivial task is borderline rediculous you could never do this sort of thing on a heaily visited site you would kill your bandwith especally since in order to do the postbacks you would also need to keep viewstate enabled for all of your textbox controls.

As for the cross browser problems if you are using .net web controls you have already accepted that you will only work properly in IE .Net will not even send down things such as style tags to other browsers if you use the cssclass property ...



0
 
LVL 28

Expert Comment

by:mmarinov
Comment Utility
hi gregoryyoung,

I know perfectly what is the output code in the web pages!
I don't know what is the goal of Rog so i just answer him to the question - as i said before if the page that the aswked functunality will be coded is big the total calculationon the server is not good approach - but if the page contains only textboxes for a calculation or whatever is not bad - everybody has an own opinion of the way of doing his/her application

as for the "browser problems" - i don't know what is your experience in the designing pages not only for IE with web controls,but  if you want to finish your job right and make your site be the same on the most using browsers it is not a problem.

B..M
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
Is ASP.NET cross-browser compatible?
ASP.NET will provide multiple types of HTML depending on the browser. 'UpLevel' browsers (IE4.0+) will get HTML4.0 and Client-Side JavaScript 1.0. All other browsers ('DownLevel') will get HTML3.2 and no JavaScript. That is as of Beta 1

Note that although I am not sure at present last time I checked (abut  year or so ago Netscape was NOT considerred an uplevel browser by default) hopefully this has changed in 2k3
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
I do want to do it on the client side.  Sorry about that earlier comment.  I made a mistake.

Javascript will be fine, but I want to use web form textbox though.


Rog
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
using a webform textbox is completely ok ... is this being done in a user control or on a actual page ?
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
grr I keep doing that ... hitting ok before I finish my thought ...

you can rather easily write a function to take a dynamic number of webform textbox objects and write them out to an array of strings for access in javascript (using the full generated control name as it is available) and then use that array to do your totals ... aside from that your main concern will be setting the hook on the textboxes you dynamically create. This is assume that these are dynamic ... hard coded is much simpler ...

Greg
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Basically I have four textboxes on the web form.  When the user enters or leaves any of three I want the fourth to have the sum of the other three.

I was hoping to have this done on the client side and hoping to get an example of what I need to do to accomplish this.

I have upped the point another 100 for all the info so far.

Rog
0
 
LVL 28

Expert Comment

by:iboutchkine
Comment Utility
wha is wrong with the sample that  gregoryyoung gave you in the
http://www.mcfedries.com/JavaScript/OrderTotals.asp

It does exactly what you want
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
This example uses HTML input box, but what I am looking for is something that will utilize web form text boxes.

thanks,

Rog
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
web form boxes ARE html text boxes ...
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Greg,


This is a webform Textbox in html...

<asp:TextBox id="txtTelDepRev" runat="server" Width="69px"></asp:TextBox>

This is an HTML textbox

<INPUT TYPE=TEXT NAME="PROD_SP_4.99" onChange="CalculateTotal(this.form)">

In the webform Textbox you cannot call or I can't figure out how to call a java script function.  This is what I am looking for.

Roger
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
Roger,

that is a textbox in ASPX ... Although you might be surprised that if you were to put say

<asp:TextBox id="txtTelDepRev" runat="server" Width="69px" onChange="CalculateTotal(this.form)"></asp:TextBox>

it would create an <INPUT> in HTML with that on it ... when you look at your page via a browser (view source) you will see that it simply generates an input box.

you would need to change this ...

function CalculateTotal(frm) {
    var order_total = 0

    // Run through all the form fields
    for (var i=0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        form_name = form_field.name

        // Is it a "product" field?
        if (form_name.substring(0,4) == "PROD") {

            // If so, extract the price from the name
            item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))

            // Get the quantity
            item_quantity = parseInt(form_field.value)

            // Update the order total
            if (item_quantity >= 0) {
                order_total += item_quantity * item_price
            }
        }
    }

    // Display the total rounded to two decimal places
    frm.TOTAL.value = round_decimals(order_total, 2)
}

very slightly to support the ASP.net mangled names but aside from that everything else should work great :)
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Greg,

Thanks for the code.  I have tried to implement it but this is what I get...

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC30456: 'CalculateTotal' is not a member of 'ASP.ComDeptMgtRpt_aspx'.

Here is the line it is pointing to.....


<TD style="WIDTH: 102px"><asp:textbox id="txtTelDepRev" runat="server" Width="69px" OnTextChanged="CalculateTotal(this.form)"></asp:textbox></TD>

I am doing this in Visual Studio.  I have put the javascript in the HTML under a script tag, so It should see this function.

Rog
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
you are trying to bind it to a server side event OnTextChanged

I know it is confusing dealing with server side and client side code at once ... This needs to run on the client side ... Your server side textbox creates an html input on the client side. The event you want to trap is onChange="CalculateTotal(this.form)" not OnTextChanged, it will not show up in intellisense and may even give a warning but it will write it out to the client. (You could also do this via adding an attribute at runtime to avoid this but this is simpler)
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Greg,

I do want to run it at the client side.  I want a web from textbox to run a client side script when the text box changes.  This is where I am confused.  I have posted my aspx code on the other question as you had asked but didn't get any response.


Rog
0
 
LVL 37

Expert Comment

by:gregoryyoung
Comment Utility
ill look at it tonight on the other question been busy the last day or so ... and yes this is where you are confused ... the best way I can suggest to alleviate this confusion is to go to your site with a browser ... Click view source in the browser and look at the HTML which was sent to you. The WebControls generate HTML (in this case an <INPUT> there is not HTML element of a <asp:TextBox> this is an item which is processed on the server to generate HTML.
0
 
LVL 8

Author Comment

by:Rog
Comment Utility
Here is what I ended up using.  ALong the same lines as what Greg has entered...


Each of the controls that will dynamically updating the total uses
the RegisterStartupScript, like so:

           txtBundlePackageRev.Attributes.Add("onblur", "CalcAll();")
            txtHSIARev.Attributes.Add("onblur", "CalcAll();")
            txtTelDepRev.Attributes.Add("onblur", "CalcAll();")


Anyway, onto the main function:

<script>
      function CalcAll()
       {
         document.Form1.txtTotal.value = parseFloat(document.Form1.txtTelDepRev.value) +
         parseFloat(document.Form1.txtHSIARev.value) + parseFloat(document.Form1.txtBundlePackageRev.value);
       }
       
</script>

FYI you have to make sure all items are in the proper case as javascript is caseSensitive.  

Also in the Visual Studio environment you will not get the textbox names in the context sensitive dropdown for document.form1.
0
 
LVL 2

Accepted Solution

by:
Lunchy earned 0 total points
Comment Utility
Closed, 225 points refunded.
Lunchy
Friendly Neighbourhood Community Support Admin
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now