简体   繁体   中英

FormatException was unhandled in C#

I'm learning C# by myself and I'm trying to create a simple project for learning some controls. 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.

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.

As Ian said in his comment, debug TextBox.Text and you will probably find the culprit.

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() :

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";
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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