We help IT Professionals succeed at work.

Sum Total of two TextBox

Whing Dela Cruz
on
How to add the following TextBox?

txtTotal.Text = txtTotal.Text + txtTop.Text;

+ doesn't work...
Comment
Watch Question

SILVER EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
You must convert the textual values to a numeric type in order to perform arithmetic on them. I typically suggest using one of the TryParse methods for this because you get validation that the values actually represent numbers before trying to work arithmetic against them. For example:

decimal decTotal = 0;
decimal decTop = 0;

if (decimal.TryParse(txtTotal.Text, out decTotal) &&
    decimal.TryParse(txtTop.Text, out decTop))
{
    txtTotal.Text = (decTotal + decTop).ToString();
}
else
{
    MessageBox.Show("Invalid value(s)!");
}

Open in new window

Author

Commented:
Thanks a lot Kaufmed, you gave perfect solution which I spent a lot of time... but could you extent your help? I need to have format for this like this 12,440.83
SILVER EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
Pass a "format string" to the ToString call:

...

txtTotal.Text = (decTotal + decTop).ToString("#,##0.00");

...

Open in new window


The #'s mean an optional field in the output; the 0's mean a mandatory digit in the output (i.e. if there's no valid digit to fill that position in the original value, then a zero is output for that position). If your sum were .2, then you would see 0.20 in the output. If the sum were 2000, then you would see 2,000.00 in the output.

I go here for my format strings:  http://blog.stevex.net/string-formatting-in-csharp/

Author

Commented:
Fast and Perfect... Thanks a lot!

Explore More ContentExplore courses, solutions, and other research materials related to this topic.