Hello All,
It's been a while since I started coding in C# so please bare with me. Here's the scenario:
I have a form that has textbox fields such as "Qty, Price, and Total Amount".
"Qty" needs to be multiplied to "Price" and the results shown in the "Total Amount" textbox.
I would like to do it in C# codebehind but using Javascript would suffice.
Aspx Code is as follows:
===================
QTY Text Box:
<asp:TextBox runat="server" name="qty100" ID="qty100" MaxLength="7" Width="70px" style="text-align:right" onkeyup='total(this,100);'></asp:TextBox>
Price Text Box:
<asp:TextBox runat="server" name="price100" ID="price100"
MaxLength="10" Width="55px" style='text-align:right' onkeyup='totalPrice(this,100);' onfocus='this.value="$"' >
Total Amount TextBox:
<asp:TextBox runat="server" name="amount100" ID="amount100" MaxLength="14" Width="120px" style='text-align:right' value='$0.00' onpropertychange='grandTotal();' ReadOnly="true">
Javascript Functions:
=====================
function total(qty,itemNo)
{
if(isNaN(val=parseInt(qty.value)*parseFloat(document.forms[0].elements["price"+itemNo].value.substr(document.forms[0].elements["price"+itemNo].value.indexOf("$")+1))))
document.forms[0].elements["amount"+itemNo].value="$0.00";
else
document.forms[0].elements["amount"+itemNo].value="$" + FormatTotal(val,0);
}
function totalPrice(price,itemNo)
{
if(isNaN(val=parseInt(document.forms[0].elements["qty"+itemNo].value)*parseFloat(price.value.substr(price.value.indexOf("$")+1))))
document.forms[0].elements["amount"+itemNo].value="$0.00";
else
document.forms[0].elements["amount"+itemNo].value="$" + FormatTotal(val,0);
}
function grandTotal()
{
var gt=0;
for(i=0;i<document.forms[0].elements.length-54;i+=7)
{
gt+=parseFloat(document.forms[0].elements[i+36].value.substr(1));
}
document.forms[0].elements["grndtotal"].value="$" + FormatTotal(gt,-1);
}
Issue with Javascript:
=====================
On my local I get the following error once I type anything in one of the text boxes....I think it's because it's blank/null before it fires...how to fix??
Line: 551
Error: 'document.forms.0.elements[...].value' is null or not an object
Also, Would really like to write it in C# code behind but I keep getting the following error:
System.FormatException: Input string was not in a correct format.
Code in C# file:
protected void price100_TextChanged(object sender, EventArgs e)
{
int a = int.Parse(qty100.Text);
int b = int.Parse(price100.Text);
int c = a * b;
amount100.Text = c.ToString();
}
Hope that makes sense and thank you very much!!
~MG

6 answers
Hi it seems the JS is throwing the error meaning the element is not null.
try moving your js to just before the end of the </body> tag.
or you ca write code to only execute js on page load.
please note : if you want me to give you a fully server side solution please ask and I will provide and answer with using only server side controls and server side script.
answered one year ago by:
753
0
Would you be kind enough to provide the server side solution please?? This doesn't seem to be working, which is funny because my elements are 'NULL'. They are blank plain textboxes. I'm tearing the few hairs I have out...
I am Assuming Visual Studios 2010 with C# 4.0
however this will most likely work in older versions.
here is C# and asp.net example on what you doing : note - please create a new project and ensure this is the solution you are looking for. If I have misunderstood you let me know.
1. Create a new asp.net Website
add in your Default.aspx if it has not been added in automatically.
We will you use 1x labels, 2x textboxes, 1x button
in my default.aspx :
Default.aspx.cs
answered one year ago by:
753
Hi there,
Great code. Much appreciated but I found a way to finally get it working for me (as you'll see below).
Let me ask you this though, if I am calculating string fields as mentioned above and they have a '$' , how can I do it then?
~(Here's the scenario: I have a form that has textbox fields such as "Qty, Price, and Total Amount")
Once Qty and Price is entered in textbox the Total Amount textbox shows qty * price = $0.00. (i.e. $1.25) and as the values are added for each row it gets tallied in the GrandTotal TextBox with the $ sign...
The first pass works OK but I can't figure out for the life of me how to remove it then calculate on the others:
HTML Code:
==========
<asp:TextBox runat="server" name="price100" ID="price100"
MaxLength="10" Width="55px" style='text-align:right'
OnTextChanged="price100_TextChanged" AutoPostBack="true"></asp:TextBox>
Here is the C# code behind: << this one's good
======================
protected void price100_TextChanged(object sender, EventArgs e)
{
decimal result;
result = Convert.ToDecimal(qty100.Text) * Convert.ToDecimal(price100.Text);
amount100.Text = "$" + result.ToString();
grndtotal.Text = "$" + result.ToString();
itm3.Focus();
}
HTML Code:
==========
<asp:TextBox runat="server" name="price101" ID="price101"
MaxLength="6" Width="55px" style='text-align:right'
OnTextChanged="price101_TextChanged" AutoPostBack="true">
Here is the C# code behind: << this one's NOT so good and so forth...
======================
protected void price101_TextChanged(object sender, EventArgs e)
{
//amount100.Text.Replace("$", string.Empty);
decimal result, total;
result = Convert.ToDecimal(qty101.Text) * Convert.ToDecimal(price101.Text);
amount101.Text = result.ToString();
total = Convert.ToDecimal(amount100.Text) + Convert.ToDecimal(amount101.Text);
grndtotal.Text = "$" + total.ToString();
itm4.Focus();
}
Thank you, your time and efforts are MUCH APPRECIATED :)
~MG
answered one year ago by:
0
Hi,
First I will create a method that will split the currency symbol and the amount.
whenever I am creating methods my mind-set is like this :
I want this method to be re-usable in all of my code and effective for my current project.
Second : using the function
answered one year ago by:
753
Hi A_O,
Great code and I think it will work perfectly. Although I would like to output the grand total into the grndTotal.Text - textbox and not Response.Write(answer). In other words here's what I have:
QTY 1 PRICE1 AMOUNT1
QTY2 PRICE2 AMOUNT2
QTY3 PRICE3 AMOUNT3
ETC........................................................................................................................................
grndTotal.Text = $0.00
As the qty and prices are tallied to the amount I need for it to also tally up the GrandTotal as well, all in the same pass.
AMOUNT1 = $35.00 + AMOUNT2 = $25.99 + AMOUNT3 = $10.00 (GRANDTOTAL = $70.99)
Thank you once again,
~MG
answered one year ago by:
0
753
Hi, I was used response.write to illustrate for my example. you can just say MyTextBoxName.Text = "string value"; to get it in there.
753
in code tags put the ASP.NET markup from your .aspx page and I can get the correct names and append my solution for those names. ( don't worry about attaching the aspx.cs )
0
DUH!! Shame on me. I was using MyTextBoxName.Text(answer); Hahahaah, must've been the looong weekend!! I'll let you know how it all turns out. Thanks again :) ~MG
Hi Again A_O,
ASPX Code for Qty, Price, and Amount:
=============================
ASPX Code for GrandTotal TextBox:
==========================
Current C# Code Behind:
==================
With "ALL" Your Code applied is giving following error:
=======================================
Index and length must refer to a location within the string.
Parameter name: length
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: Index and length must refer to a location within the string.
Parameter name: length
Source Error:
Line 156: private string[] RenderAmount(string ammount)
Line 157: {
Line 158: string[] s = { ammount.Substring(0, 1), ammount.Substring(1, ammount.Length - 1) };
Line 159: return s;
Line 160: }
Thanks,
~MG
answered one year ago by:
0