-2
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.

MethodMan
  • 18,625
  • 6
  • 34
  • 52
Sean
  • 3
  • 1
  • 2
    Add a breakpoint and debug. You can see where the code generates the error. – Luud van Keulen Sep 27 '16 at 20:25
  • The error is on the Convert.ToInt32 but i'm unsure how to rectify the error. As far as I know I'm converting the string to an int, calculating the sum and then reconverting it back to a string – Sean Sep 27 '16 at 20:31
  • 1
    try using `try.Parse` instead of `Convert.ToInt32()` – MethodMan Sep 27 '16 at 20:33
  • 1
    When you want to parse text to an integer its a good idea to use tryParse. You can find more information about that [here](https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx) – Luud van Keulen Sep 27 '16 at 20:33
  • In addition to using `TryParse`, you need to use your `ResultString` AFTER your calculation. See my answer below. – Icemanind Sep 27 '16 at 20:39

4 Answers4

2

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();
Icemanind
  • 47,519
  • 50
  • 171
  • 296
1

Icemanind's solution is very good, but you can consider not allowing the user to enter incorrect number from the beginning (something like a numeric text box). Several solutions are shown here:

private void FirstNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}

Also, you should consider overflowing (* may easily get past Int32.MaxValue for numbers large enough), as it may lead to unexpected results, as shown here:

try
{
    checked
    {
        // may be used for all operations

        int product = num1 * num2;
    }
}
catch(OverflowException ex)
{
    resultBox.Text = "Integer operation overflow";
}

OR

Declare product as Int64 to make sure it accommodates all possible results.

Thus, you can be almost certain that you have valid numbers in your text boxes.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
  • This is good. Only issue is it can still allow for empty values (unless the textbox has a default value of 0 or something) – Icemanind Sep 27 '16 at 21:01
  • Yes, checking for empty is still needed. Also, parsing trials are needed, since user may paste the numbers from somewhere (unless pasting is disabled). So, this should be regarded as a complementary answer to make the interface more friendly. – Alexei - check Codidact Sep 27 '16 at 21:08
0

Be sure to check for null or empty values before attempting to convert.

if(String.IsNullOrEmptry(Number2.Text))
  num2 = 0;
else
  num2 = Convert.ToInt32(Number2.Text);

You are also converting 'result' to 'resultString' before you are setting a the answer to 'result.' You should move

resultBox.Text = resultString;

To below the if-else block.

hogarth45
  • 3,387
  • 1
  • 22
  • 27
0

you should place string resultString = Convert.ToString(result); after calculation

private void Calculate_Click(object sender, EventArgs e)
        {

            int num1 = Number1.Text==""?0:Convert.ToInt32(Number1.Text);
            int num2 = Number2.Text==""?0:Convert.ToInt32(Number2.Text);
            int result = 0;


            if (Addition.Checked == true)
            {
                result = num1 + num2;
            }
           else if (Subtraction.Checked == true)
            {
                result = num1 - num2;
            }
            else if (Multiplication.Checked == true)
            {
                result = num1 * num2;
            }
            else
            {
                resultBox.Text = "Error, no parameter selected";
            }
        string resultString = Convert.ToString(result);
            resultBox.Text = resultString;
        }
Zulqarnain Jalil
  • 1,679
  • 16
  • 26