【问题标题】:Exception ; An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code例外 ; mscorlib.ni.dll 中出现“System.FormatException”类型的异常,但未在用户代码中处理
【发布时间】:2013-05-27 12:16:04
【问题描述】:

您好,我有一个 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 吗?有什么问题?

【问题讨论】:

    标签: windows-phone-7 c#-4.0 windows-phone-8


    【解决方案1】:

    错误最有可能在这里:

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

    如果数字不是有效格式,它会抛出 FormatException。 (see more here)。尝试使用double.TryParse 以安全的方式解析您的值。

    double result;    
    bool success = double.TryParse(basetext.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out result);
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多