4

您好,我有一个 windows phone 8 应用程序,但我遇到了异常

mscorlib.ni.dll 中出现“System.FormatException”类型的异常,但未在用户代码中处理

这是代码

  private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        double basestolen;
        double attempedstales;
        double avarege;
        double putout;




         if (puttext.Text.Length == 0 | basetext.Text.Length==0 )
        {

            MessageBox.Show(" Enter Values for Base Stolen and Putouts ");

        }

         basestolen = Convert.ToDouble(basetext.Text);
        putout = Convert.ToDouble(puttext.Text);



        attempedstales = basestolen + putout;


        if (attempedstales != 0  )
        {

            avarege = (((basestolen / attempedstales) / 100));
            avarege = avarege * 10000;
            avgtext.Text = Convert.ToString(avarege);


        }
        else
        {
            MessageBox.Show("Attemped Stales Value should not be Zero");
        }



    }

应用程序运行,如果我没有在文本框中输入值,它会返回消息框,但之后应用程序停止并返回上面的 exption 吗?问题是什么?

4

2 回答 2

3

错误很可能在这里:

basestolen = Convert.ToDouble(basetext.Text);
putout = Convert.ToDouble(puttext.Text);

如果数字不是有效格式,它会抛出 FormatException。(在这里查看更多)。尝试使用double.TryParse以安全的方式解析您的值。

double result;    
bool success = double.TryParse(basetext.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
于 2013-05-27T12:29:23.143 回答
0

您在显示消息框后忘记停止执行您的方法:

if (puttext.Text.Length == 0 || basetext.Text.Length==0 )
{
    MessageBox.Show(" Enter Values for Base Stolen and Putouts ");
    return;
}

此外,将字符串转换为双精度时,请确保指定区域性。您的 Windows Phone 应用程序将由世界各地的用户执行,并且某些国家/地区使用不同的小数分隔符。例如:

basestolen = Convert.ToDouble(basetext.Text, CultureInfo.InvariantCulture);
于 2013-05-27T12:24:27.780 回答