Site icon KSoftLabs

How to Create a Simple Calculator in Visual Studio 2017 – Part III

Visual Srudio

We have created a Simple Calculator in part one of this tutorial and we discussed about the code and did minor adjustments to the code in part two of this tutorial.

When you examine the code you can see that we are repeating some lines again and again.

dblNumber1 = Double.Parse(txtNumber1.Text);
dblNumber2 = Double.Parse(txtNumber2.Text);

For example above two lines repeat four times in the code.

Let’s create a function that takes the operation as a parameter and carry out the function and display the results.

private void Calculate(string operation)
       {
           double dblNumber1 = 0;
           double dblNumber2 = 0;
           double dblAnswer = 0;

           dblNumber1 = Double.Parse(txtNumber1.Text);
           dblNumber2 = Double.Parse(txtNumber2.Text);

           switch (operation)
           {
               case "+":
                   dblAnswer = dblNumber1 + dblNumber2;
                   break;
               case "-":
                   dblAnswer = dblNumber1 - dblNumber2;
                   break;
               case "/":
                   dblAnswer = dblNumber1 / dblNumber2;
                   break;
               case "*":
                   dblAnswer = dblNumber1 * dblNumber2;
                   break;
           }

           txtAnswer.Text = dblAnswer.ToString();
           lblOperation.Text = operation;
       }

Here we have used a switch statement to do the related mathematical operation. You can read more about switch statement here. Declaration of variables and other codes are as explained in the previous tutorials.

Now we have to change the Click events of each button. Below is the code segment of the altered version.

private void btnAdd_Click(object sender, EventArgs e)
{
    Calculate("+");
}

private void btnSub_Click(object sender, EventArgs e)
{
    Calculate("-");
}

private void btnDiv_Click(object sender, EventArgs e)
{
    Calculate("/");
}

private void btnMulti_Click(object sender, EventArgs e)
{
    Calculate("/");
}

private void btnClear_Click(object sender, EventArgs e)
{
    txtNumber1.Text = "";
    txtNumber2.Text = "";
    txtAnswer.Text = "";
    lblOperation.Text = "?";
}

Here we are calling the Calculate function while passing the appropriate string for operation as a variable. Now your calculator solution should work as previous version.

You might have notice that if we enter invalid inputs such as letters, special characters etc. ; the solution crashes with an error.

We can avoid this by slightly modifying the code.

private void Calculate(string operation)
{
    double dblNumber1 = 0;
    double dblNumber2 = 0;
    double dblAnswer = 0;

    if(Double.TryParse(txtNumber1.Text,out dblNumber1) && Double.TryParse(txtNumber2.Text, out dblNumber2))
    {
        switch (operation)
        {
            case "+":
                dblAnswer = dblNumber1 + dblNumber2;
                break;
            case "-":
                dblAnswer = dblNumber1 - dblNumber2;
                break;
            case "/":
                dblAnswer = dblNumber1 / dblNumber2;
                break;
            case "*":
                dblAnswer = dblNumber1 * dblNumber2;
                break;
        }

        txtAnswer.Text = dblAnswer.ToString();
        lblOperation.Text = operation;
   
    }
    else
    {
        MessageBox.Show("Invalid Input", "Input Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
    }
}

Here instead of using Double.Parse here we are using Double.TryParse. It will try to convert the given value into a double and return whether the parse operation was succeeded or not. You can read more about it here.

The returned value is then checked using an if statement. Here I have used “&&” to check whether either one of the parse operation is failed. You can read more about conditional AND operator (&&) here.

If there is an error parsing the string to double we are assuming it is to be an input error and inform the user using a MessageBox. To learn more about MessegeBox class click here.

Now if you have done everything correctly you will have a Simple Calculator project with error handling.

Exit mobile version