Public Class Form1
02
03 Dim total1 As Integer
04 Dim total2 As Integer
05
Private Sub btn3_Click(ByVal sender As System.Object, ByVal e As
06
System.EventArgs) Handles btnthree.Click
07
08 txtDisplay.Text = txtDisplay.Text & btnthree.Text
09
10 End Sub
11
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
12
System.EventArgs) Handles MyBase.Load
13
14 End Sub
15
Private Sub btn7_Click(ByVal sender As System.Object, ByVal e As
16
System.EventArgs) Handles btnseven.Click
17
18 txtDisplay.Text = txtDisplay.Text & btnseven.Text
19
20 End Sub
21
Private Sub btnzero_Click(ByVal sender As System.Object, ByVal e As
22
System.EventArgs) Handles btnzero.Click
23
24 txtDisplay.Text = txtDisplay.Text & btnzero.Text
25
26
27 End Sub
28
Private Sub btnone_Click(ByVal sender As System.Object, ByVal e As
29
System.EventArgs) Handles btnone.Click
30
31 txtDisplay.Text = txtDisplay.Text & btnone.Text
32
33 End Sub
34
Private Sub btntwo_Click(ByVal sender As System.Object, ByVal e As
35
System.EventArgs) Handles btntwo.Click
36
37 txtDisplay.Text = txtDisplay.Text & btntwo.Text
38
39 End Sub
40
Private Sub btnfour_Click(ByVal sender As System.Object, ByVal e As
41
System.EventArgs) Handles btnfour.Click
42
43 txtDisplay.Text = txtDisplay.Text & btnfour.Text
44
45 End Sub
46
Private Sub btnfive_Click(ByVal sender As System.Object, ByVal e As
47
System.EventArgs) Handles btnfive.Click
48
49 txtDisplay.Text = txtDisplay.Text & btnfive.Text
50
51 End Sub
52
Private Sub btnsix_Click(ByVal sender As System.Object, ByVal e As
53
System.EventArgs) Handles btnsix.Click
54
55 txtDisplay.Text = txtDisplay.Text & btnsix.Text
56
57 End Sub
58
Private Sub btneight_Click(ByVal sender As System.Object, ByVal e As
59
System.EventArgs) Handles btneight.Click
60 txtDisplay.Text = txtDisplay.Text & btneight.Text
61
62 End Sub
63
Private Sub btnnine_Click(ByVal sender As System.Object, ByVal e As
64
System.EventArgs) Handles btnnine.Click
65 txtDisplay.Text = txtDisplay.Text & btnnine.Text
66
67 End Sub
68
Private Sub cmdPlus_Click(ByVal sender As System.Object, ByVal e As
69
System.EventArgs) Handles cmdPlus.Click
70
71 total1 = total1 + Val(txtDisplay.Text)
72
73 txtDisplay.Clear()
74
75 End Sub
76
Private Sub cmdEquals_Click(ByVal sender As System.Object, ByVal e As
77
System.EventArgs) Handles cmdEquals.Click
78
79 total2 = total1 + Val(txtDisplay.Text)
80 txtDisplay.Text = total2
End Sub
End Class
I think I figured it out. Here is what I did.
view source
print?
1 total1 = btnzero.Text
I can't believe it took me a whole day to figure that out.
This tutorial will teach you:-
-Simple Arrays
-Manipulating numbers
-Implementing summing
Let's begin. Firstly we need to create the interface. So you'll need to crank
up ole VB. Put a text box up the top, clear it and give it a decent name like
txtDisplay, now we need to create the numbers, these will be command buttons
and must be an array, the easiest way to do this is to just create one button,
copy and paste it, and when the system asks do you want to create a control
array, you click yes! But what is and array? Well simply put it is a collection
of related variable that share the same type.
Do this for all the numbers 0
through 9, just like on Windows own calculator. Now you need to do the same
for the methods of calculation, the - + * etc. Now you should have something
that resembles a calculator. Of course these aren't the only buttons you'll
need dont forget the equals sign and of course some form of clear, I use C just
like Windows' own calculator. And now onto some coding.
We are going to need three variables, one for the first number of type double
(to hold large numbers.) one for the second number, and of course one for the
sign, or type of calculation we are doing. This is how I have declared them.
Dim first As Double
Dim second As Double
Dim sign As String
Not to bad so far, let's get those nasty arrays out of the way.
Private Sub Command1_Click(Index As Integer)
If txtDisplay.Text = "" Then
txtDisplay.Text
= Command1(Index).Caption
Else
txtDisplay.Text
= txtDisplay.Text & Command1(Index).Caption
End If
End Sub
This is the array, what this does is makes the content of the display screen
equal to the caption that has been clicked. In other words if you click the
button with 1 on it the number one will go to the display text box. The same
applies for the following array sub.
Private Sub Command2_Click(Index As Integer)
first = txtDisplay.Text
txtDisplay.Text = ""
sign = Command2(Index).Caption
End Sub
Now what this does is assign the value of the display to the first variable,
this makes it nice and easy to manipulate two numbers, it's my tip of the day,
next it clears the content of the display box and then assigns the sign to the
sign variable. And now for a minimal effort at keeping the user from crashing
it.
Private Sub Form_Load()
txtDisplay.Enabled = False
txtDisplay.MaxLength = 10
End Sub
On form load set max length of the text box to 10 and dont let anything get
stuck in the text box by any other method then hitting the command buttons.
Now lets see our hard work pay off by adding the calculation sub.
Private Sub cmdEq_Click()
second = txtDisplay.Text
If sign = "-" Then
txtDisplay.Text
= first - second
ElseIf sign = "+" Then
txtDisplay.Text
= first + second
ElseIf sign = "*" Then
txtDisplay.Text
= first * second
ElseIf sign = "/" Then
txtDisplay.Text
= first / second
End If
End Sub
Firstly the sub assigns whats in the display to the variable named second.
It then works out what calculation should be done by finding the current value
for the sign variable, so if the variable is / then it will devide the first
number by the second. And that in essence is the calculator, not to bad I thought,
and easy enough for you to build on and create a much more complex one. There
are a few mor subs we should explore but don't deserve any special attention.
Private Sub cmdDot_Click()
If InStr(txtDisplay.Text, ".") = 0 Then
txtDisplay.Text = txtDisplay.Text & "."
End If
End Sub
This tests if there is a . in the box before adding one.
Private Sub cmdClear_Click()
txtDisplay.Text = "0"
End Sub
Resets the display box.
This is all there is to writing a simple calculator program in VB it's barely
a page worth of actual code.
What you should have learned :-
-Array use
-Simple error cactching
-Using numbers in Visual Basic with mathematical calculations
Public Class Form1
Dim s = 0, a As Integer
Dim op As String
Dim b As String
Dim c As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
a=1
TextBox1.Text = "1"
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button3.Click
a=2
TextBox1.Text = "2"
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
a=3
TextBox1.Text = "3"
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button5.Click
a=4
TextBox1.Text = "4"
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button4.Click
a=5
TextBox1.Text = "5"
End Sub
Private Sub Button9_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button9.Click
a=6
TextBox1.Text = "6"
End Sub
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button7.Click
a=7
TextBox1.Text = "7"
End Sub
Private Sub Button11_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button11.Click
a=8
TextBox1.Text = "8"
End Sub
Private Sub Button10_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button10.Click
a=9
TextBox1.Text = "9"
End Sub
Private Sub Button12_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button12.Click
a=0
TextBox1.Text = "0"
End Sub
Private Sub Button14_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button14.Click
s = Integer.Parse(TextBox1.Text)
op = "+"
TextBox1.Text = ""
End Sub
Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button8.Click
s=0
a=0
TextBox1.Text = a.ToString()
End Sub
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button13.Click
s = Integer.Parse(TextBox1.Text)
op = "-"
TextBox1.Text = ""
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button6.Click
If op = "+" Then
s = s + Integer.Parse(TextBox1.Text)
End If
If op = "-" Then
s = s - Integer.Parse(TextBox1.Text)
End If
If b = "*" Then
s = s * Integer.Parse(TextBox1.Text)
End If
TextBox1.Text = "0"
TextBox1.Text = s.ToString()
s=0
End Sub
Private Sub Button15_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button15.Click
s = Integer.Parse(TextBox1.Text)
b = "*"
End Sub
Private Sub Button16_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button16.Click
s = Integer.Parse(TextBox1.Text)
c = "/"
TextBox1.Text = ""
End Sub
End Class
/w EPDw UKMTY2
Search
New Member FAQ | Forums | Earn Revenue
Practice Ask Question
Resources Jobs English Projects Universities Colleges Courses Schools Training
Tests Experts Papers
Gift Shop | Bookmarks | Reviews | Business
Directory | Lobby | Communities | Classifieds | Mentors | Links | New Posts | My
India | Members | Polls |
My Profile
Resources » Articles/Knowledge Sharing » Computer &
Sign In
Technology »
Registe
r
AdSens
e Revenue
How To Create a
Calculator in Visual
Awards &
Gifts Basic.Net
Posted Date: Resource Type: Category:
16 Sep Articles/Knowledge Computer &
2009 Sharing Technology
Active Members
Author: Kiran
Today Member Level:
Paul
Diamond
vimal Kanikaram
(241)
Rating:
ankit Points: 45 (Rs 35)
(168)
krishna
(104)
Last 7 Days
R Online Members
Pramod ankit
(3015) Tony
babu Thanga perumal "Your's
(2469)
Friend"
vimal
Shathish kumar
(1230)
srinivas raju
jay
more... Chharugh Konwar
Rajeev Pathak
More...
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 appear 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. Your form should now resemble
like this.
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 If
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
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
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
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.
A Tester's Blog
Attachments
calculator Code (86486-16434-VB calculator
code.pdf)
Responses to the resource: "How To
Create a Calculator in Visual Basic.Net"
No responses found. Be the first to respond and
make money from revenue sharing program.
Subscribe to Feedbacks Un Subscribe
Feedbacks
What
Popular are Search
tags Tags
Tags
?
How To Create a Calculator in Visual
Basic.Net . Calculator code in
VB . Visual Basic Code .
Post Feedback
This is a strictly moderated forum. Only approved
messages will appear in the site. Please use 'Spell
Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next
More Resources
Resource:
Convert any
Convert any
movie format
movie format to
to 3GP
3GP
Previous
Useful tips on
Resource:
website creation
Checking to earn money
Usability online
Features in a
How to convert
Web
MS Word file to
Application
PDF file
while Testing
Design Pattern
Return to Interview
Resources Questions - Part
3
Post New
Resource Hardware
Category: TuneUp Utilities
2009 How to
Computer &
make your pc
Technology
run faster With
high
performance
Post resources and
earn money!
About Us Contact Us Revenue Sharing sites Advertise Privacy Policy Terms Of Use
ISC Technologies, Kochi - India
2006 - 2010 All Rights Reserved.