简体   繁体   English

在C#中未处理FormatException

[英]FormatException was unhandled in C#

I'm learning C# by myself and I'm trying to create a simple project for learning some controls. 我正在独自学习C#,并且试图创建一个用于学习一些控件的简单项目。 And I'm coding my project just like my book, but I get an error. 而且我像在编写书一样对项目进行编码,但出现错误。 Could anyone help me? 有人可以帮我吗? Thank you... 谢谢...

Error: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format. 错误:mscorlib.dll中发生了'System.FormatException'类型的未处理异常。其他信息:输入字符串的格式不正确。

My code: 我的代码:

private void button1_Click(object sender, EventArgs e)
    {
        int sum = 0;
        float average = 0;
        sum += Convert.ToInt32(textBox1.Text);
        sum += Convert.ToInt32(textBox2.Text);
        sum += Convert.ToInt32(textBox3.Text);
        average = (float)sum / 3;
        textBox4.Text = average.ToString();
    }

My project 我的项目

It is likely due to the values being placed in the TextBoxes. 这可能是由于将值放置在TextBoxes中。

As Ian said in his comment, debug TextBox.Text and you will probably find the culprit. 正如伊恩(Ian)在评论中所说,调试TextBox.Text,您可能会找到罪魁祸首。

For more information, it will likely be very useful for you to check out this previous question . 有关更多信息,这对于您检查上一个问题可能非常有用。

One of the answers to that question gives the idea of using TryParse() : 该问题的答案之一是使用TryParse()的想法:

int a = 0;
if (!int.TryParse(TextBox.Text, out a))
{
    // Couldn't parse input to an integer, show a message perhaps?
}

See code below: 参见下面的代码:

private void button1_Click(object sender, EventArgs e)
{
  try
  {
    int sum = 0;
    float average = 0;
    sum += Convert.ToInt32(textBox1.Text);
    sum += Convert.ToInt32(textBox2.Text);
    sum += Convert.ToInt32(textBox3.Text);
    average = (float)sum / 3;
    textBox4.Text = average.ToString();
  }
  catch(FormatException exc)
  {
    textBox4.Text = "ERROR";
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM