- Back to Home »
- C# Tutorial »
- C# Calculator - The Equals Button
Posted by : senan
Friday, February 14, 2014
The Equals button is where the action takes place. This is where
we will do the actual addition.
To store the answer to the addition, we'll need another variable (in blue bold
below):
double total1 = 0;
double total2 = 0;
private void btnPlus_Click(object sender, EventArgs e)
{
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
txtDisplay.Clear();
}
So set up a total2 variable in your code, as we've done above.
Return to your Form, and double click the Equals button to get at your code.
Now add the following three lines of code:
total2 = total1 + double.Parse( txtDisplay.Text );
txtDisplay.Text = total2.ToString( );
total1 = 0;
txtDisplay.Text = total2.ToString( );
total1 = 0;
The first line should look familiar:
total2 = total1 + double.Parse( txtDisplay.Text );
To the right of the equals sign, we're doing the same thing as before:
total1 + double.Parse(txtDisplay.Text);
The difference is before the equals sign: we're now storing it in the total2
variable:
total2 = total1 + double.Parse(txtDisplay.Text);
In other words, get the number from the text box, convert it to a double variable,
add it to whatever is in total1. When all this is worked out, store the answer
in the variable called total2.
The second line of code was this:
txtDisplay.Text = total2.ToString( );
On the right of the equals sign, we're converting the total2 variable
To a String. This is so that it can be displayed as Text in the text box.
The third line of code resets the total1 variable to zero:
total1 = 0;
This is so a new sum can be calculated.
Time to try out your calculator. Use it to calculate the following:
10 + 25
36 + 36
10 + 10 + 10
36 + 36
10 + 10 + 10
In the next section, we're going to move on to something called Conditional
Logic. We'll use Conditional Logic to complete the calculator. You will then
be able to use it to divide, subtract, and multiply. So make sure you save the
work you've done so far!