我想用下面的语句来总结3个文本框的值,但是我似乎无法使它工作。 3个文本框的值显示为十进制。 错误:mscorlib.dll中发生未处理的“System.FormatException”类型异常附加信息:输入字符串的格式不正确。
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);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);最满意答案
问题中的细节不够,但我的直觉告诉我这是问题所在:
您在文本框中的内容像40,5 ,但计算机当前文化已将小数点分隔符设置为。(点) 。 因此,在将40,5转换为小数时会出现异常,因为它不明白,。
它可能是另一种方式,你正在写40.5,但它期望得到40.5。
编辑
我看到了关于Florian von Spiczak的评论,并且似乎字符$出现在文本框中。 如果是这样,那显然是一个问题。
尝试使用textBox.Text.Replace("$","")替换Convert.ToDecimal调用中的所有textBox.Text 。 这应该摆脱$并使其正确解析。
所以完整的代码应该是:
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;此外,您应该用decimal.Parse或decimal.TryParse替换Convert.ToDecimal ,并在文本decimal.TryParse实际写入的内容上添加验证逻辑。
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.
更多推荐
发布评论