How To Create A Calculator In Visual Basic



Visual Basic Calculator: We are going to create a “first program” that will be written in Visual Basic (VB). If you set Calculator on scientific mode, you have access to the same operators as in.NET. For detail you can visit this is a very simple code to check the number is prime or not Dim i, j As Integer. Basic Calculator. In the previous sections, we displayed text in console window (black background window). In this section, you will learn to use window forms and other useful components and controls to create GUI applications that increase interactivity. Step1: Create a project (Windows Forms Application) File-New- Project.

The calculator above was created after I did some work crunching out the code and searching the Internet for solutions where I got stuck. Thanks to the generosity of the programming fraternity, I managed to come up with something to the best of my amateur ability. I still got stuck with one portion of the code, which I will indicate later.

Following is the full code for this program, and I call it: QuickCalc.

_____________________________________________________________________________________________

First and foremost, arrange all the necessary command buttons and a textbox onto a Form. For the textbox, I set it to read-only, and text to “0” (zero, not the letter O), named it txtInput.

Next, some essential global declarations.

1.‘Variables to hold operands.
2.Private dblValue1 As Double
3.Private dblValue2 As Double
4.‘Variable to hold temporary values.
5.Private dblTemp As Double
6.‘True if “.” is used, otherwise false.
7.Private blnDecimalPoint As Boolean
8.Private blnInputStatus As Boolean
9.‘Variable to hold Operator.
10.Private strCalculate As String

Next, the code for Number buttons 1 – 9.

1.If (blnInputStatus AndAlso txtInput.Text <> “0”) Or blnDecimalPoint Then
2.txtInput.Text += cmd1.Text
3.Else
4.txtInput.Text = cmd1.Text
5.blnInputStatus = True
6.End If

The above code is for button number 1. For 2 to 9, simply change the cmd number to the respective button number.

Next, the code for Number button 0.

1.If blnInputStatus Then
2.‘To prevent multiple zeroes from appearing if 0 is the first digit.
3.If txtInput.Text.Length >= 1 AndAlso txtInput.Text <> “0”Then
4.txtInput.Text += cmd0.Text
5.‘This is to allow 0 to be added after the decimal point.
6.ElseIf blnDecimalPoint Then
7.txtInput.Text += cmd0.Text
8.End If
9.End If

Next, the code for Decimal button.

1.‘To make sure that no decimal point has already been input.
2.If Not blnDecimalPoint Then
3.‘For values > 0 but < 1.
4.If txtInput.Text.Length < 1 Then
5.txtInput.Text = “0.”
6.Else
7.txtInput.Text += “.”
8.End If
9.
10.blnInputStatus = True
11.‘To ensure only one decimal point per calculation.
12.blnDecimalPoint = True
13.End If

Next, the code for the Addition operator.

1.If txtInput.Text.Length <> 0 Then
2.‘Check the value of the function flag.
3.If strCalculate = String.Empty Then
4.‘Assign the value in the input box to the holder.
5.dblValue1 = CType(txtInput.Text, Double)
6.txtInput.Text = “0”
7.Else
8.‘Call the CalculateTotals method.
9.CalculateTotals()
10.End If
11.
12.‘Assign a value to the function flag.
13.strCalculate = “Add”
14.
15.‘Toggle the decimal flag.
16.blnDecimalPoint = False
17.End If

The code for the Subtraction, Multiplication, and Division operators are almost identical, except that you need to change the value assigned to the function flag – Subtract, Multiply, Divide – respectively.

Next, the code for Equal button.

1.If txtInput.Text.Length <> 0 Then
2.CalculateTotals()
3.strCalculate = String.Empty
4.blnDecimalPoint = False
5.End If

Next, the code for the Exponential button.

1.If txtInput.Text.Length <> 0 Then
2.If strCalculate = String.Empty Then
3.dblValue1 = CType(txtInput.Text, Double)
4.txtInput.Text = “0”
5.Else
6.CalculateTotals()
7.End If
8.strCalculate = “Exponential”
9.blnDecimalPoint = False
10.End If

Next, the code for the Square Root button.

1.If txtInput.Text < “0”Then
2.MsgBox(“The root of a negative number is undefined!”, 0, “WARNING”)
3.Exit Sub
4.End If
5.
6.If txtInput.Text.Length <> 0 Then
7.dblTemp = CType(txtInput.Text, Double)
8.dblTemp = System.Math.Sqrt(dblTemp)
9.txtInput.Text = CType(dblTemp, String)
10.blnDecimalPoint = False
11.End If

Next, the code for the Reciprocal button.

1.If txtInput.Text.Length <> 0 Then
2.dblTemp = CType(txtInput.Text, Double)
3.dblTemp = 1 / dblTemp
4.txtInput.Text = CType(dblTemp, String)
5.blnDecimalPoint = False
6.End If

Next, the code for the Positive/Negative button.

1.If txtInput.Text.Length <> 0 Then
2.dblTemp = CType(txtInput.Text, Double)
3.dblTemp *= -1
4.txtInput.Text = CType(dblTemp, String)
5.End If

Next, the code for the Clear All (C) button.

1.txtInput.Text = “0”
2.dblValue1 = 0
3.dblValue2 = 0
4.strCalculate = String.Empty
5.blnDecimalPoint = False

Next, the code for the Clear Entry (CE) button.

1.txtInput.Text = “0”
2.blnDecimalPoint = False

Next, the code for the Backspace button.

1.‘Declare locals needed.
2.Dim str As String
3.Dim intNumbers As Integer = txtInput.Text.Length
4.
5.If txtInput.Text.Length = 1 Or (txtInput.Text.Length = 2 AndAlso
6. txtInput.Text.StartsWith(“-“)) Then
7.txtInput.Text = “0”
8.Exit Sub
9.End If
10.
11.If txtInput.Text.Length > 0 Then
12.‘Get the next to last character.
13.str = txtInput.Text.Chars(txtInput.Text.Length – 2)
14.‘Check if it’s a decimal.
15.If str = “.”Then
16.‘If it is, then toggle the blnDecimalPoint flag.
17.blnDecimalPoint = False
18.txtInput.Text = txtInput.Text.Remove(intNumbers – 2)
19.Exit Sub
20.End If
21.txtInput.Text = txtInput.Text.Remove(intNumbers – 1)
22.End If

Finally, the CalculateTotals procedure.

1.dblValue2 = CType(txtInput.Text, Double)
2.Select Case strCalculate
3.Case“Add”
4.dblValue1 += dblValue2
5.Case“Subtract”
6.dblValue1 -= dblValue2
7.Case“Multiply”
8.dblValue1 *= dblValue2
9.Case“Divide”
10.If dblValue2 = 0 Then
11.MsgBox(“You cannot divide by 0!”, 0, “WARNING”)
12.Exit Sub
13.End If
14.dblValue1 /= dblValue2
15.Case“Exponential”
16.dblValue1 ^= dblValue2
17.End Select
18.txtInput.Text = CType(dblValue1, String)
19.blnInputStatus = False

_____________________________________________________________________________________________
Above is the code for this calculator program.

How

!PROBLEM!
However, there is an area which I have some niggling issues with.

1. For the + – * / and ^ operators, if I were to click on one of them multiple times after I input the first value, they will go performing the operation on their own without me entering the second value. How do I stop this from happening?

I have been learning Visual Basic .Net and have been trying to create many applications and I just wanted to put down what I have learned and this application would be a lot of help for those who are interested into programming or learning to code.
The Calculator application is the most common application being asked in the examinations and also in the technical interview for job aspirants and I have found this one to be very useful and the code is also very simple and easy to learn and when actually starts creating it would be fun.
I am putting down every thing in detail and in step by step form and also I would try to put in some images for easy understanding so that one would find its approach very easy and quick to learn. Also please find an attachment in pdf format of the code for calculator but a not of caution don't just copy paste the code but following step by step will actually help you to understand what is been done behind the code.
First of all you need to have Microsoft Visual Basic 6 or more or visual basic.net installed on your system. Open the application and it will display a start page if you do not have any other applications created. Now just follow the steps mentioned.
1. From the file menu select 'Standard EXE' from the new project menu (Visual basic 6). If working on Visual Basic. Net then from the File menu select New Project. You will see a blank form appearing on the screen.
2. Rename your project and your form by clicking on 'Project1' at the right hand side of the screen in the Solution Explorer window or in the project listing as per the version of the VB. Enter a new name in the 'Name' line of the Properties box, which should appear below the project listing by default. Press 'Enter' to accept the new name. Do the same for your form (a suggested form name is ‘Calculator'), making sure to enter a similar name in the 'Caption' property as well, which will change the text in the top bar of the form. Save the project in a new folder on your computer.
3. Now you have a form displayed on the screen and also on the left side you would see the toolbox menu items. If you do not find it the go to the View Menu and click Tool bar and select the standard menu item. The tool box is displayed. Add the required buttons and a text box to the form.
First add a text box in which the numbers are entered and also the results of calculations is displayed when the calculator appear. Select the Text Box button from the toolbar at the left side of the screen, and then drag with your mouse to the location you desire for the Text Box.
Once you've placed the Text Box you can change the size and location by dragging it to another location of the form or by dragging the handles (the small squares) along the border of the TextBox. Be sure to change the following lines in the Properties window, with the TextBox selected: '(Name)' = tbResult, 'Alignment' = 1- Right Justify, 'Data Format' = (click on the '...' button to select) Number, 'Locked' = True, and 'Text' = 0.
4. Select the Button icon on the toolbar and create the first button just like the way you created the Text Box. For quick reference use the Windows calculator in Standard view. You can view this by going to Programs > Accessories > Calculator as a base for your calculator layout.
We are not adding the 'MC', ‘MR', ‘MS' and ‘M+' buttons. For each button change the following properties using the '+' button as an example. Change the properties of Name as ‘btnPlus', Caption or Text as ‘+'. Do the same for the rest of the calculator buttons and save your work.
5. Now let's start adding some code to make the calculator work. Please note that your buttons and textbox should be named the same as the code listed here or else you will need to change the names to match your buttons and textbox to match this code. First we need to create a few variables for processing calculator input:
Dim aLeft As String, aRight As String, aOperator As String
Dim iLeft As Double, iRight As Double, iResult As Double
Dim bLeft As Boolean
Each calculation consists of four parts: a number to the left of the operator (aLeft, iLeft), an operator (aOperator), a number to the right of the operator (aRight, iRight), and a result (iResult). In order to track whether the user is entering the left or right number, we need to create a boolean variable, bLeft. If bLeft is true, the left side of the calculation is being entered; if bLeft is false, the right side is being entered.
6. Initialize the bLeft variable. We do that by creating a Form_Load subroutine, which you can either type as listed here or automatically create by double-clicking on any part of the form not covered by a button or textbox. Inside the function, we need to set bLeft to True, because the first number entered will be the left part:
Private Sub Form_Load()
bLeft = True
End Sub
7. Now we need to create a subroutine that will handle the clicking of any of the number buttons. This subroutine we be used for each of the number button and should be after the End Sub of the Form Load because we use identical code for each button, and using a subroutine means not having to repeat the same code ten times. Enter the following below the Form_Load subroutine's End Sub line:
Private Sub AddNumber(sNumber As String)
If bLeft Then
aLeft = aLeft + aNumber
tbResult.Text = aLeft
Else
aRight = aRight + aNumber
tbResult.Text = aRight
End If
End Sub
From the above we see that this function takes a string parameter, aNumber, which will contain the number the user has clicked on. If bLeft is true, this number is appended to the string that represents the number being entered, aLeft, and the textbox, tbResult, is updated to display the new number. If bLeft is false, the same operation is performed using aRight instead.
Finally, create a Click event function for each number that calls our AddNumber subroutine. You can do this easily by double-clicking each number button, which will create the subroutine structure for you. Then add the call to AddNumber, replacing the number in quotes with the number associated with the button. For the zero button, your code will look like this:
Private Sub btn0_Click()
AddNumber ('0')
End Sub
Likewise, for the one button, your code will look like this
Private Sub btn1_Click()
AddNumber ('1')
End Sub
Like wise create the subroutine for all other numbers.
8. To handle the operators plus, minus, times, and divide. We will do this step, creating a subroutine that is called in the Click events for the operator buttons. The subroutine will look like the following:
Private Sub AddOperator(sNewOperator As String)
If bLeft Then
aOperator = sNewOperator
bLeft = False
Else
btnEquals_Click (this should be used only in Visual Basic 6. If the same is there in the VB.net it will throw error. Make a note of it)
aOperator = sNewOperator
aRight = '
bLeft = False
End If
End Sub
If bLeft is true, meaning the user has just entered the left part of the calculation, this subroutine sets the aOperator variable we created in step 5 to equal the operator entered, which is passed to AddOperator as the string sNewOperator. The second step is to set bLeft to False, because the entry of an operator means the user is done entering the left side of the equation.
In order to handle entries that string multiple operators together, such as 9 * 3 * 2 * 6, we need to also check whether bLeft is false, meaning the user has entered an operator where we were expecting an equals. First we call the Click event for the equals button (described in the next step), which does the calculation and sets tbResult to the result of what has already been entered. Then we clear aRight so the user can enter the next number, and set bLeft to False so the program knows we are entering the right hand side of the calculation next.
Add an AddOperator call to the Click event of each operator button, using the same method as we used in step 7 to create the Click events for the number buttons. Your code for the plus button will look like this:
Private Sub btnPlus_Click()
AddOperator ('+')
End Sub
Likewise, the code for the minus button will look like this:
Private Sub btnMinus_Click()
AddOperator ('-')
End Sub
9. Create the Click event for the equals button, which is the most complex code in this program. Create the subroutine structure like you did for the other buttons, by double-clicking the equals button on your form.
Here in this subroutine we will use the case syntax because based on the button click the code should run. So the case statement will select the button clicked like plus, minus, divide, multiply etc and will perform the condition mentioned for that particular case. So the advantage of the case syntax is that it will directly go to the required condition. Your subroutine will look like this when you've entered the code:
Private Sub btnEquals_Click()
If aLeft <> ' And aRight = ' And aOperator <> ' Then
aRight = aLeft
End IfBasic
If sLeft <> ' And aRight <> ' And aOperator <> ' Then
iLeft = aLeft
iRight = aRight
Select Case sOperator
Case '+'
iResult = iLeft + iRight
Case '-'
iResult = iLeft - iRight
Case '/'
iResult = iLeft / iRight
Case '*'
iResult = iLeft * iRight
End Select
tbResult.Text = iResult
aLeft = iResult
aRight = '
bLeft = True
End If
End Sub
The first three lines of code check to see if both sides of the calculation have been entered along with an operator. If only the left side and an operator are entered, the value of the left side is copied to the right, so we can mimic the standard calculator behavior for handling an entry like 9 * =, which multiplies 9 by itself to get a result of 81.
The rest of the code will run only if left, right, and operator are entered, and starts out by copying the strings of numbers into our iLeft and iRight Double-typed variables, which can do the actual calculations. The Select Case statement allows us to run different code depending on which operator was entered, and performs the actual calculation, placing the result in iResult. Finally, we update the textbox with the result, copy the result into aLeft, reset aRight, and set bLeft = True.
These last lines allow us to take the result of the calculation and use it to perform another calculation.
10. Now we will look at the last three operation buttons: sqrt, %, and 1/x. For the Click event of the square root button, your code will look like this:
Private Sub btnSqrt_Click()
If aLeft <> ' Then
iLeft = aLeft
Else
iLeft = 0
End If
If aRight <> ' Then
iRight = aRight
Else

Visual Basic Tip Calculator

iRight = 0
End If
If bLeft Then
iLeft = Math.Sqr(iLeft)
tbResult.Text = iLeft
Else
iRight = Math.Sqr(iLeft)
tbResult.Text = iRight
End If
If iLeft <> 0 Then
aLeft = iLeft
Else
aLeft = '
End If
If iRight <> 0 Then
aRight = iRight
Else
aRight = '
End If
End Sub
A point to be noted is that when the square root function is run then in the iLeft = Math.Sqr(iLeft), iRight = Math.Sqr(iLeft) lines sqr to be changed to sqrt if using VB.net.
The first 11 lines of code make sure that if we don't have a value entered for either side of the equation, we substitute zero instead of trying to copy an empty string into iLeft or iRight, which will generate an error. The middle lines perform the square root function on the current part of the calculation, either left or right. Finally, we reverse the checks we did in the beginning so that a zero is copied as an empty string back into aLeft and aRight.
For the percent button, the code is similar, with one exception: the percent operation can only be performed if both left and right sides are entered.
Private Sub btnPercent_Click()
If Not bLeft Then
If aRight <> ' Then
iRight = aRight
Else
iRight = 0
End If
iRight = iRight * (iLeft / 100)
tbResult.Text = iRight
If iRight <> 0 Then
aRight = iRight
Else
aRight = '
End If
End If
End Sub
Lastly, the 1/x, or fraction, Click event, which is very similar to the code above:
Private Sub btnFraction_Click()
If aLeft <> ' Then
iLeft = aLeft
Else
iLeft = 0
End If
If aRight <> ' Then
iRight = aRight
Else
iRight = 0
End If
If bLeft Then
iLeft = 1 / iLeft

How To Create A Calculator In Visual Basic C++


tbResult.Text = iLeft
Else
iRight = 1 / iRight
tbResult.Text = iRight
End If
If iLeft <> 0 Then
aLeft = iLeft
Else
aLeft = '
End If
If iRight <> 0 Then
aRight = iRight
Else
aRight = '
End If

How To Create A Calculator In Visual Basic 2010

End Sub
11. Lets add some code to handle the C and CE buttons. C clears all input to the calculator, whereas CE only clears the number currently being entered.
Private Sub btnC_Click()
aLeft = '
aRight = '
aOperator = '
tbResult.Text = '0'
bLeft = True
End Sub
Private Sub btnCE_Click()
If bLeft Then
aLeft = '
Else
aRight = '
End If
tbResult.Text = '0'
End Sub
12. Here we are now we are ready with the calculator and can run your calculator program and do any calculation you wish. Now by putting in extra effort and some thinking this calculator can be easily expanded to handle more operations, more complex calculations or even to be a scientific calculator.