Sean Sean - 2 months ago 18
C# Question

Trying to create a form calculator using C#, unsure of "System.FormatException" error

namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Calculate_Click(object sender, EventArgs e)
{
int num1 = Convert.ToInt32(Number1.Text);
int num2 = Convert.ToInt32(Number2.Text);
int result = 0;
string resultString = Convert.ToString(result);

if (Addition.Checked == true)
{
result = num1 + num2;
resultBox.Text = resultString;
}
else if (Subtraction.Checked == true)
{
result = num1 - num2;
resultBox.Text = resultString;
}
else if (Multiplication.Checked == true)
{
result = num1 * num2;
resultBox.Text = resultString;
}
else
{
resultBox.Text = "Error, no parameter selected";
}
}
}
}


I'm pretty sure that most of it is right, it seems to be the converting that is tripping me up. I'm new to C# (first day!) so i'm a bit confused. Also first post on this website, so sorry for any formatting problems.

Answer

It sounds like an issue with trying to convert to a number. Instead of using Convert.ToInt32(), try TryParse() instead:

int num1;
int num2;
bool isNum1Valid = int.TryParse(Number1.Text, out num1);
bool isNum2Valid = int.TryParse(Number2.Text, out num2);

if (!isNum1Valid)
{
    // num1 is invalid. Throw an error message or something
}

if (!isNum2Valid)
{
    // num2 is invalid. Throw an error message or something
}

Your other issue in your code is that your converting ResultString before you are parsing the result. Use this line AFTER you do your calculation:

string resultString = result.ToString();