I am trying to sum the values from 3 textboxes with the following statement, however i cant seem to get it working. The 3 textboxes have values displayed decimal. Error: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.
decimal num1, num2, num3, total;
num1 = Convert.ToDecimal(SSubTotalTextBox.Text);
num2 = Convert.ToDecimal(SubTotalMTextBox.Text);
num3 = Convert.ToDecimal(SubTotalTextBox3.Text);
total = num1 + num2 + num3;
TotalAmountTextBox.Text = Convert.ToString(total);
Instead of Convert.ToDecimal try:
That should help you find out what's wrong with the input of your textboxes.
the best way is to use decimal.TryParse() method, then you could do some validations. MSDN: Decimal.TryParse Method (String, Decimal)
Did you enter values in all textboxes? Convert may not like empty strings. You can also try decimal.Parse or decimal.TryParse instead of Convert.
Edit: I don't think that culture is a problem, yet. Even if it's entered with 6,4 and the culture expects 6.4 the , will usually be interpretet as thousand seperator and would result in 64 instead of 6.4.
It not enough details in the question, but my gut feeling tells me this is the problem:
You have the content in the textbox like 40,5, but the computers current culture has the decimal seperator set to .(dot). Therefore you get an exception while converting 40,5 to a decimal, since it does not understand ,.
It could be the other way around and you are writing 40.5, but it expect to get 40.5.
EDIT
I saw the comment on Florian von Spiczak answer, and it seems that the character $ is present in the textboxes. If it is, that is obviously a problem.
Try to replace all the
textBox.Text
inside theConvert.ToDecimal
calls withtextBox.Text.Replace("$","")
. That should get rid of the $ and make it parse properly.So the complete code should then be:
Also, you should replace
Convert.ToDecimal
withdecimal.Parse
ordecimal.TryParse
, and add some validation logic on what is actually written inside your textboxes.