C# Statement Textboxes Sum

2019-06-23 18:01发布

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);

4条回答
一夜七次
2楼-- · 2019-06-23 18:40

Instead of Convert.ToDecimal try:

 decimal dec1;
 if (!Decimal.TryParse(SSubTotalTextBox.Text, dec1)
 {
    MessageBox.Show("Error trying to convert to a decimal: " + SSubTotalTextBox.Text);
 }

That should help you find out what's wrong with the input of your textboxes.

查看更多
Explosion°爆炸
3楼-- · 2019-06-23 18:40

the best way is to use decimal.TryParse() method, then you could do some validations. MSDN: Decimal.TryParse Method (String, Decimal)

查看更多
Bombasti
4楼-- · 2019-06-23 18:43

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.

查看更多
放荡不羁爱自由
5楼-- · 2019-06-23 19:01

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 the Convert.ToDecimal calls with textBox.Text.Replace("$",""). That should get rid of the $ and make it parse properly.

So the complete code should then be:

decimal num1, num2, num3, total;
num1 = Convert.ToDecimal(SSubTotalTextBox.Text.Replace("$",""));
num2 = Convert.ToDecimal(SubTotalMTextBox.Text.Replace("$",""));
num3 = Convert.ToDecimal(SubTotalTextBox3.Text.Replace("$",""));
total = num1 + num2 + num3;
TotalAmountTextBox.Text = "$ "+ total;

Also, you should replace Convert.ToDecimal with decimal.Parse or decimal.TryParse, and add some validation logic on what is actually written inside your textboxes.

查看更多
登录 后发表回答