我收到此错误。这是代码
double totalfees = Convert.ToDouble(textBox12.Text);
double paidfees = Convert.ToDouble(textBox13.Text);
double pendingfees = totalfees - paidfees;
label20.Text = pendingfees.ToString();
我该怎么办?
答案 0 :(得分:0)
请尝试以下。
double totalfees = Convert.ToDouble(textBox12.Text.ToString().Trim());
double paidfees = Convert.ToDouble(textBox13.TextToString().Trim());
double pendingfees = totalfees - paidfees;
label20.Text = pendingfees.ToString();
或者使用double.TryParse()
代替。这是进行转换的更好方法。
答案 1 :(得分:0)
在使用parse方法之前,请使用TryParse,如下面的代码:
double totalFees;
if (Double.TryParse(textBox12.Text, out totalFees) == false)
throw new Exception("Invalid value unable to parse into double");
答案 2 :(得分:0)
由于用户可以将任何字符串作为回复(例如"bla-bla-bla"
),我们应该验证输入;让我们提取方法:
private static bool ReadDouble(Control control, bool allowEmpty, out double value) {
if (allowEmpty && string.IsNullOrWhiteSpace(control.Text)) {
value = 0.0;
return true;
}
bool result = double.TryParse(control.Text, out value);
if (!result) {
if (control.CanFocus)
control.Focus();
MessageBox.Show("Invalid value; floating point value expected",
Application.ProductName,
MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
return result;
}
然后你可以放一个简单的
if (ReadDouble(textBox12, false, out var totalfees) &&
ReadDouble(textBox13, true, out var paidfees))
label20.Text = (totalfees - paidfees).ToString();
else
label20.Text = "???";