Visual Basic Tutorial - Create A Simple Calculator Application
Visual Basic Tutorial - Create A Simple Calculator Application
In this tutorial we will create a simple calculator to Add/Subtract/Multiply and Divide two numbers
and show a simple message box result.
Lets get started
First create a new Visual Basic Windows Form Project
This is what the code view looks like at the moment. We dont have any code to run except the Form
1 class there. All the code for this program will go inside that class.
We need to create two different variables first. These variables will be used to store the numbers
from each text box. I know you are already thinking about integers; well you are not wrong we do a
number variable however we want one that can hold decimal numbers and not just whole numbers.
Public Class Form1
Dim numA As Double
Dim numB As Double
End Class
Integers hold numbers such as 1, 2, 30, 45, 67542 its all whole numbers but since we have a division
button on the mix we will need to a simple division calculation and with an integer we cannot do
that. So double variables can hold numbers such as 1.2 , 12.221211 and so on.
Now go back to the design view and double click on the plus button.
Once you double clicked on the button, visual studio will automatically add the line of code in your
project. These lines are now linked to the button 1 which is out plus sign.
Now lets add the following code inside this function
numA = Convert.ToDouble(TextBox1.Text)
This line is calling the numA variable we created earlier and storing some value inside it. Now since
the user will be using those text boxes to enter the numbers they want to calculate they will be
stored as Text or Strings. Now we cannot do maths with strings because well you know why. Anyhow
since our numA variable is a double we will have to convert them to a double type of data and store
them inside it. Hence the line Convert.ToDouble() Inside the brackets we can put in our target which
we want to convert in this instance its the Textbox1 and we are looking for the value which the user
has put inside it thats the text portion of Textbox1 hence its Textbox1.Text.
numB = Convert.ToDouble(TextBox2.Text)
Doing the same thing as above except with numB and TextBox2.Text
Now then how can we view our result to the user? We will use a text box.
Lets try this
MessageBox.Show(numA+numB) since its adding the values together
That worked.
Now lets go back and double click on the Minus, Multiply and Divide button and add the following
code
Public Class Form1
Dim numA As Double
Dim numB As Double
Notice where the symbols changed for the calculations, its inside the message boxes.
Here are the results
See the decimal is working in the end. Now go make something else. MOOOO