Complete Calculator in C Sharp
Complete Calculator in C Sharp
Step 4 Now, we start working with the display, usually when the calculator starts
it should display the number 0. In our case it does not. So we modify the Text
Property and write 0 in that. Make sure you don’t add any spaces before or after
the 0. The second thing to note is that the number is aligned to the left, while
calculators align the number to the right. Search for the TextAlign property and
change it to Right. See image above.
4
Calculator App in C Sharp
Step 5 Now, we start working with the code, we want to call a method which
add the specific number to the text field when it is clicked and we want that
operation for every button from 0 to 9. So, here we write a function which will
be called on every button click from 0 to 9.
Step 6 In the next step, we have declared four variable at class level for using
in the different methods. See image below.
5
Calculator App in C Sharp
Step 7 In the next step, we want to call a method which will work with operator’s
(+,-,*,/ and %) when the specific operator is clicked the symbol of that operator
is saved in a variable called operatorString and the number from text field is
saved in a variable firstNumber and the text filed text is set to 0.
We have added a label above text field to show the number and operation in
code snippet below last line set the first operand and operator on the label. See
image below.
Step 8 In the next step, we want to add minus sign in front of number for this
we have attached PlusMinus_Click Method is called with PlusMinus button and
following code is used for plus and minus.
6
Calculator App in C Sharp
Step 9 In the next step, we want to add dot(decimal) between for this we have
attached Dot_Click Method is called with Dot button and following code is used
for decimal(dot).
7
Calculator App in C Sharp
Step 10 In the next step, we want to call a method Equal_click() which will work
when the equal button is clicked. In this method we first saved the
secondNumber from text Box text. We have used switch case based on
operatorString variable and in different cases we have performed the required
operation. in the last the resultNumber variable is assigned to textField text and
answer of operation is assign to the label See image below.
8
Calculator App in C Sharp
Step 9 In the last step, we want to reset all information as we click on clear [c]
button. Textfield is set to zero and other variables are reset to their initial state.
See image below.