Jump to content

[C# Tutorial For Beginners] How to make a calculator


Eagle Scripts

Recommended Posts

Heya,

 

I just learned this so I thought i should share this with you guys. This is for the people that have never worked with Visual Studios C# programming before.

 

This is what your end product will look like (or simillar, depending on your own design preference)

1d2e201e7f.png

 

First of all, open Microsoft Visual Studio

 

1. Making a new Project

    - Go to --> File --> New --> Project --> Click Visual C# --> Windows Forms Application

    - Change the name to something like 'calculator'.

    - Let the solution name change itself.

    - Obviously, hit OK afterwards.

 

2. This is what you should start with 
     65b9015785.png

 

3. Changing the name & size of our Calculator

    - In the right bottom right you can see the properties of your selected item. If you do not see this, click the Form1 application once or       right-click properties.

    - To change the name we're going to change its Text in the properties. Scroll down in the properties untill you find its Text. Change        this to 'Calculator' or something like that. Be sure to change its Text and not its name, since these are two different things which            i'll be explaining lateron.

    

    - To change its size, you can simply Drag the Calculator to your desired size or you can change its size in the properties.

      The size I used for my calculator is 
      Width 426, Height 404

 

4. This is what your Calculator should look like after doing steps 1 - 3

    5af2e7f78f.png

 

5. Adding the Textpanel

    - First of all, your Calculator needs Textpanel to show the answers of the calculations ofcourse.

    - We'll do this by opening the Toolbox at first. Navigate to --> View --> Toolbox.

    - The Toolbox is shown now, with the Toolbox you can add various things such as buttons.

    - Search the Toolbox until you find the 'RichTextBox', drag&drop it into your Calculator.

    - Change its size to your desired size.

    - Change its name to something like 'tbAnswer' (since its a textbox and we're going to show our answer in it)

 

6. Adding our Buttons

    - Search for a button in the Toolbox and drag&drop it into your Calculator.

    - Give it any size and place you want.

    - Change its Text to '1' and its name to something like 'bt1'. (since it's a button and it's for the number '1')

       The name is what the button will be 'called' or 'recognised' as.

    - Do this for all the other buttons aswell;

       2, 3, 4, 5, 6, 7, 8, 9, 0, Calculate, CE, +, -, * , / and '.'

    - Your result would look like this:

       1d2e201e7f.png

7. Making our buttons do something

    - Firstly, we'll need to define some objects. 

string input = string.Empty;        //String storing user input
        string operand1 = string.Empty;     //String storing first operand
        string operand2 = string.Empty;     //String storing second operand
        char operation;                     //char for operation
        double result = 0.0;                //calculated result

  Write the code above this message between

public partial class Form1 : Form
    {

  and 

 public Form1()

 like this --> 

d420b26a31.png

I've written some quick information about the objects in the green colored text.

 

 - Now we need to 'link' our buttons with a piece of code. To do this, you have to Double-Click on the button itself.

 - Do this for all the buttons.

 - Visual Studio has now made a private void for every button.

    It should look like this. 

private void btn1_Click(object sender, EventArgs e)
{

}

- Obviously, we should add some code so the private void actually has an action to perform.

- To make the btn0 result a '0' once its clicked, we can use something like this:

private void btn0_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";    
            input = input + "0";
            tbAnswer.Text = tbAnswer.Text + input;

        }

//tbAnswer

is our Textbox. We need to define this on top so the Textbox starts with a 'clean line', with no text. (otherwise clicking multiple times on the 0-button wouldn't add multiple 0's.

 

//input

We defined a String, input. We defined it as an empty String but we're going to give the string some 'information' to store.

The new input will be : the current input + "0".

This means, if the input has been defined as 0 (because we've clicked the 0-button), and we click the 0-button again it will change to

"00" instead of staying at "0".

 

//tbAnswer.Text

is our text which is linked and shown in our Textbox-Answer. 

We define our new tbAnswer's Text to: the current tbAnswer Text + our new defined input.

 

- Do this for all numbers so your result will be:

private void btn0_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "0";
            tbAnswer.Text = tbAnswer.Text + input;

        }

        private void btn1_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "1";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "2";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn3_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "3";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn4_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "4";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn5_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "5";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn6_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "6";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn7_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "7";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn8_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "8";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn9_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "9";
            tbAnswer.Text = tbAnswer.Text + input;
        }

- Now, we need to give our operation buttons a action aswell (+,-,* etc.)

  We need to do this a little differently, take a look at the following code:

private void btnPlus_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '+';
            input = string.Empty;
        }

 //operand1

   will be set to the 'information' our defined input carried with it.

   our operation will be '+'.

   we will clean our defined input, we define it as a Empty String once more, we need to do this because we need to have 2 sides of          numbers to be able to count this above each other. (example ; 3 + 3 = 6 , 1 number on the left of the our operation '+' and one on        the right)

 

- Do this for all of the operation buttons, i'm not telling you what to do with the dot-button & CE-Button. You'll have to think about this yourself. If you can't figure out, look at the code below. (It's easy!)

  It should look like this:

private void btnmin_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '-';
            input = string.Empty;
        }

        private void btnPlus_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '+';
            input = string.Empty;
        }

        private void btnKeer_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '*';
            input = string.Empty;
        }

        private void btngedeelddoor_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '/';
            input = string.Empty;
        }

        private void btnPunt_Click(object sender, EventArgs e)
        {
            input = input + ".";
        }

        private void btnCE_Click(object sender, EventArgs e)
        {
            input = string.Empty;
            tbAnswer.Text = "";
        }

 

- Now, we have 1 button left to give a action it should perform on a Click, the Calculate button.

- This one is actually a big one, and will probably be hard for you to understand.

- We need to define a few more objects for the Calculate button. Do this in the Calculate's Click method!

operand2 = input;
double num1, num2;
double.TryParse(operand1, out num1);
double.TryParse(operand2, out num2);

//operand2

  Will be defined as the 'information' input caried within it.

  

//doubles

  doubles are numbers with decimals (Example : 4,21)

 

- Now, every operation needs its own action it should perform. We are doing this with if & else cases, just like Java.

  

For our '+' operation:

If the operation is +, we should add the num1 and num2 together, right? This is how that would look like in code:

if (operation == '+')
            {
                result = num1 + num2;
                tbAnswer.Text = result.ToString();
            }

//result

  We are defining result to: The answer of num1 + num2

 

//result.ToString()

  The result we defined, would be an answer of numbers, which is an int.

  The .Text method only works with Strings (multiple characters, like a text. Example: "Heya")

  Because the .Text method only works with String we need to change our answer , which is an int, to a String.  

 

- For the '-' operation it would be:

 else if (operation == '-')
            {
                result = num1 - num2;
                tbAnswer.Text = result.ToString();
            }

//else if

  This is because there can only be one 'if', all the others should either be 'else if' or 'else'.

 

- Make all the actions for the remaining operations.

 

 

- The full code of your Calculate button should look like this:

private void btnCalculate_Click(object sender, EventArgs e)
        {
            operand2 = input;
            double num1, num2;
            double.TryParse(operand1, out num1);
            double.TryParse(operand2, out num2);

            if (operation == '+')
            {
                result = num1 + num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '-')
            {
                result = num1 - num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '*')
            {
                result = num1 * num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '/')
            {
               
                    result = num1 / num2;
                    tbAnswer.Text = result.ToString();
                

            }
        }

- Now, if you've done everything like I did, your Calculator should work!

- Try it out! Click on the 'Play' button on the top.

 

- The full code: 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {

        string input = string.Empty;        //String storing user input
        string operand1 = string.Empty;     //String storing first operand
        string operand2 = string.Empty;     //String storing second operand
        char operation;                     //char for operation
        double result = 0.0;                //calculated result

        
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {
            operand2 = input;
            double num1, num2;
            double.TryParse(operand1, out num1);
            double.TryParse(operand2, out num2);

            if (operation == '+')
            {
                result = num1 + num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '-')
            {
                result = num1 - num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '*')
            {
                result = num1 * num2;
                tbAnswer.Text = result.ToString();
            }
            else if (operation == '/')
            {
               
                    result = num1 / num2;
                    tbAnswer.Text = result.ToString();
                

            }
        }

        private void btn0_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "0";
            tbAnswer.Text = tbAnswer.Text + input;

        }

        private void btn1_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "1";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "2";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn3_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "3";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn4_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "4";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn5_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "5";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn6_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "6";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn7_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "7";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn8_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "8";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btn9_Click(object sender, EventArgs e)
        {
            tbAnswer.Text = "";
            input = input + "9";
            tbAnswer.Text = tbAnswer.Text + input;
        }

        private void btnmin_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '-';
            input = string.Empty;
        }

        private void btnPlus_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '+';
            input = string.Empty;
        }

        private void btnKeer_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '*';
            input = string.Empty;
        }

        private void btngedeelddoor_Click(object sender, EventArgs e)
        {
            operand1 = input;
            operation = '/';
            input = string.Empty;
        }

        private void btnPunt_Click(object sender, EventArgs e)
        {
            input = input + ".";
        }

        private void btnCE_Click(object sender, EventArgs e)
        {
            input = string.Empty;
            tbAnswer.Text = "";
        }
    }
}

Edited by Eagle Scripts
  • Like 6
Link to comment
Share on other sites

liked for C# wub.png


if anyone is interested in C# applications, check out these

 

http://osbot.org/forum/topic/91098-release-startupfile-either-for-lazy-people-or-for-people-that-dont-know-how-to

http://osbot.org/forum/topic/89971-quickstart-released/

http://osbot.org/forum/topic/92065-release-autoshutdown/

 

also made a program in C# for a OSRS streamer

 

http://www.twitch.tv/iamkeeferz/v/37649131?t=05m47s

 

 

if anyone has any questions go ahead and ask doge.png


to add to OP:

 

you should create a seperate class for variables to keep your application clean, like this

 

as you can see i have 2 classes in the folder Value object. 

3c84305468.png

 

it's neccecary to do this with bigger applications, so that your program won't become spaghetti. it's also nice to work organized.

 

 

once you have the class, you can call the variable from anywhere, this is what i love about this method

57c6106c59.png

 

5b4794d7ca.png

 

requirements:

  • Make the property static

 

the way you described it:

d420b26a31.png

 
 
it might be a little complicated for starters, but i advice you to try and understand wink.png
Edited by The Hero of Time
  • Like 1
Link to comment
Share on other sites

  • 2 months later...

 

liked for C# wub.png

if anyone is interested in C# applications, check out these

 

http://osbot.org/forum/topic/91098-release-startupfile-either-for-lazy-people-or-for-people-that-dont-know-how-to

http://osbot.org/forum/topic/89971-quickstart-released/

http://osbot.org/forum/topic/92065-release-autoshutdown/

 

also made a program in C# for a OSRS streamer

 

http://www.twitch.tv/iamkeeferz/v/37649131?t=05m47s

 

 

if anyone has any questions go ahead and ask doge.png

to add to OP:

 

you should create a seperate class for variables to keep your application clean, like this

 

as you can see i have 2 classes in the folder Value object. 

3c84305468.png

 

it's neccecary to do this with bigger applications, so that your program won't become spaghetti. it's also nice to work organized.

 

 

once you have the class, you can call the variable from anywhere, this is what i love about this method

57c6106c59.png

 

5b4794d7ca.png

 

requirements:

  • Make the property static

 

the way you described it:

d420b26a31.png

 
 
it might be a little complicated for starters, but i advice you to try and understand wink.png

 

 

Don't want to put ya down or anything, but what you're explaining is either poorly worded or blatantly wrong. It goes against basic OOP concepts.

 

Static abusing isn't something you should be encouraging, or creating new classes to keep your variables tidy, the correct way I suppose of saying this would be if you consider each class its own object (which it is), then each object should only contain its required variables.

 

And yeah, i'm a little late on the reply :)

Link to comment
Share on other sites

  • 3 weeks later...

Why is

tbAnswer.Text = "";
input = input + "0";
tbAnswer.Text = tbAnswer.Text + input;

not a method?

 

I also think the buttons should have been created at run-time to reduce the clutter.

At the time of writing this tutorial, i was / am still a beginner myself in C#. Just thought i'd share what i had learned, i'm sure there's plenty of better ways to go with it though (:

 

C# is cancer...   <  C/C++ .

Nice tut tho

Thanks smile.png

 

c# really isn't that bad tbh.

 

Solid tutorial too, nice smile.png

Thanks smile.png​ 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...