Visual Basic Calculator Code using Control Arrays


This article is written by Pon Saravanan  on 09-Sep-09 Last modified on :19-Jan-10





VB calculator code

This article is mainly for the beginners. I am trying to explain the use of Control Arrays with the help of Calculator Sample.I feel control arrays are overlooked  in classic visual basic. if the way to implement is understood, it is much useful in reducing the code. Control Arrays can be used in the situations like whenever the need of same controls being used several times in an application. We can make them as an array, and the controls can be accessed by their index in all the respective events

VB 6 Control Arrays in form

As shown in the following figure, Design the form. Create a Command Button named as Command1 and copy that and paste it 11 times. This will create a control array.
Then assign the text as shown in the figure. all the controls under red boxes are under one group. So design it accordingly.

like wise create cmdOperator control array for the green box group.

Now you can use the sample code to try


VB Calculator

we actually storing the Last Operator used and The first part of the number used in a class level variable. so that they can be accessed across the events and functions. Since the operators also created as control arrays. we had drastically reduced the amount of code required for a simple calculator.

Source Code - Simple(VB 6.0)

Private LastOperator  As String
Private FirstPart As String

Private Sub cmdClear_Click()
    FirstPart = ""
    LastOperator = ""
End Sub
Private Sub cmdEquals_Click()
Select Case LastOperator
    Case Is = "+"
        Text1.Text = FirstPart + Text1.Text
    Case Is = "-"
        Text1.Text = FirstPart - Text1.Text
    Case Is = "/"
        Text1.Text = FirstPart / Text1.Text
    Case Is = "*"
        Text1.Text = FirstPart * Text1.Text
End Select
    FirstPart = ""
    LastOperator = ""
End Sub
Private Sub cmdOperator_Click(Index As Integer)
    LastOperator = cmdOperator(Index).Caption
    FirstPart = Text1.Text
    Text1.Text = ""
End Sub
Private Sub Command1_Click(Index As Integer)
    Text1.Text = Text1.Text + Command1(Index).Caption
End Sub


Source Code - Enhanced Calculator(VB 6.0)

Now few places we need to lock the Calculator stop entering invalid entries. If not done then runtime error will be thrown. To prevent entering the alpha characters the textbox can be locked by enabled=false. 

For improved usability, we can hook the keyboard to handle most of the keystrokes to minimize the use of mouse. After enabling KeyPreview in the Form, all the key strokes will be routed through the form. So handling event of form’s keypress will be able to handle the keyboard keys.

Source Code - Enhanced Calculator(VB 6.0)

Private LastOperator  As String
Private FirstPart As String
Private Sub Form_Load()
    txtResult.Enabled = False
    Me.KeyPreview = True
End Sub
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
    ' numbers in main keyboard
    If (KeyCode >= 48 And KeyCode <= 57) Then
        AddDigits (Chr(KeyCode))
    End If
   
    ' numbers in numpad
    If (KeyCode >= 96 And KeyCode <= 105) Then
        AddDigits (Chr(KeyCode - 48))
    End If
   
    'if backspace
    If (KeyCode = 8) Then
        If (txtResult.Text <> "") Then
        txtResult.Text = Left(txtResult.Text, Len(txtResult.Text) - 1)
        End If
    End If
    'for various operators
    If (KeyCode = 111) Then RegisterOperator ("/")
    If (KeyCode = 106) Then RegisterOperator ("*")
    If (KeyCode = 109) Then RegisterOperator ("-")
    If (KeyCode = 107) Then RegisterOperator ("+")
End Sub
Private Sub cmdOperator_Click(Index As Integer)
    RegisterOperator (cmdOperator(Index).Caption)
End Sub
Private Sub cmdClear_Click()
    FirstPart = ""
    LastOperator = ""
    txtResult.Text = ""
   
End Sub
Private Sub cmdEquals_Click()
    Select Case LastOperator
        Case Is = "+"
            txtResult.Text = FirstPart + txtResult.Text
        Case Is = "-"
            txtResult.Text = FirstPart - txtResult.Text
        Case Is = "/"
            txtResult.Text = FirstPart / txtResult.Text
        Case Is = "*"
            txtResult.Text = FirstPart * txtResult.Text
    End Select
        FirstPart = ""
        LastOperator = ""
End Sub
Private Sub Command1_Click(Index As Integer)
    AddDigits (Command1(Index).Caption)
End Sub
 
Private Sub AddDigits(Digit As String)
    txtResult.Text = txtResult.Text & Digit
End Sub
Private Sub RegisterOperator(OperatorText As String)
    LastOperator = OperatorText
    FirstPart = txtResult.Text
    txtResult.Text = ""
End Sub



« Previous -







Comments
  • GUEST
    hi thanks 9/16/2009 7:28:10 AM

  • GUEST
    wow nice tnx i can use this 10/19/2009 1:00:37 AM

  • GUEST
    i really need to know how to use or make a code for my project..we're
    planning to do some program which is cybercafe program but we really dont know how to use coding..we're done with our interface..the problem is the coding..
    10/27/2009 7:23:44 AM

  • GUEST
    ..tnx a lot!! 1/24/2010 7:12:37 PM

  • GUEST
    Thanks a lot 2/15/2010 11:22:27 PM

  • GUEST
    thnx buddies 3/22/2010 10:46:15 AM

  • GUEST
    really helpful, but i do not get the cmdCleat button too work 4/21/2010 1:51:07 AM

  • pons
    It actually clears all the operators and the results. So that it will reset the calculator.
    Hope that helps you to understand. If not please elaborate more on where exactly you are unable to understand.

    Thanks
    4/21/2010 2:13:49 AM

  • GUEST
    Thank u soo much....I really need it..
    6/3/2010 7:23:32 AM

  • GUEST
    good day!
    thanks for this sample code...
    i got an idea from this..
    6/14/2010 6:12:05 AM

  • GUEST
    well 7/26/2010 7:23:02 AM

  • GUEST
    tnz u very much 8/9/2010 7:15:50 PM

  • GUEST
    hi 9/26/2010 1:02:19 AM

  • GUEST
    i'm not sure what your variable are exactly, like what is: Private Sub RegisterOperator(OperatorText As String) 9/27/2010 11:39:26 AM

  • GUEST
    I dont understand your question, Can you please be more specific? 9/27/2010 6:48:26 PM

  • GUEST
    code of simple calculator in vb
    9/29/2010 9:27:18 PM

  • GUEST
    I need some help coding a simple calculator without the number buttons.

    It is setup with a text box (as display) and 6 buttons ( +, -, *, /)(C and CE)

    Can someone help me get started out atleast..?
    10/2/2010 3:29:25 PM

  • pons
    If you dont have number buttons and text box is only for display, how will you get the numbers to work on? Do you recieve it from externaly(from otherforms?)

    10/3/2010 2:12:26 AM

  • GUEST
    thnx...jejejeje
    10/7/2010 7:51:35 AM

  • GUEST
    tnx!!... ^_^
    10/17/2010 8:28:15 PM

  • GUEST
    thanks you're indeed helpful...^_^ gamsahamnida 11/26/2010 7:55:02 PM

  • GUEST
    Thank u very much am use this code its working very nice 12/17/2010 2:47:05 AM

  • GUEST
    thank u very much am use this code its working very nice -------k.deepa 12/17/2010 2:47:48 AM

  • GUEST
    THKS 12/27/2010 2:57:51 AM

  • GUEST
    how do you add an operation that solves the exponent?
    the symbol looks like this " ^ ".
    2/17/2011 4:55:35 PM

  • pons
    I dont have 'Classic Visual Basic' installed in my machine. I checked in .Net and the excel macro(close to vb i guess) i can conclude that MsgBox(8 ^ 3) produces 512. So hope that helps. If not please explain your questions in detail.

    Thanks
    2/17/2011 6:13:15 PM

  • GUEST
    thanks a lot. . . . . . . . . . . . . . . . . . 2/24/2011 5:57:16 PM

  • GUEST
    Thanks a Lot ;) 3/8/2011 4:29:55 AM

  • GUEST
    I needed to understand listbox arrays (and how to manipulate them) and couldnt find the specific help I needed so I'm using this tutorial to help me understand how to manipulate arrays in general.
    I have followed the examples as given, but the command operator (+) just displays the first and second number, it does'nt add them together, it just displays which numbers were selected. All other operators work as expected. Looking at the code, I cant see why this would be, it's supposed to add them both together and give the result.

    It's indicative of a problem I had with another project I was working on. It required arrays in listbox form. The problem I was having there was I only wanted calculations happening to 1 element of the array when selected from the form, the problem being all elements of the array would chime in with their calculations, even when just trying to manipulate just 1. I clearly have a problem with arrays I just dont understand how to work with them. Was wondering if (with the above explantion in mind) you could point me to a resource which explains to the beginner how to manipulate and work with arrays? I have looked, but I have yet to find a resource which is specific enough for me to use as an example. Thanks for any help.
    3/9/2011 9:40:42 PM

  • pons
    The reason why the (+) operator fails can be due to the datatype mismatch. You may change the following line

    from
    ------
    Text1.Text = Text1.Text + Command1(Index).Caption

    to
    Text1.Text = cInt(Text1.Text) + cInt(Command1(Index).Caption)

    This will cast both the strings to integer before applying the specific operation.
    BTW which version of visualbasic are you using?
    You may refer to the following MSDN Link for more information on arrays
    http://msdn.microsoft.com/en-us/library/wak0wfyt(v=vs.80).aspx

    Feel free to discuss here. It will help future readers who may have encountered the same issue as you.
    3/9/2011 11:00:04 PM

  • GUEST
    Hi, thanks for the response. I'm using VB6. I know I should be using a later version but I've only just started with this stuff (I had a copy of VB6 lying around and it was quicker to get going with that). I really am a rank newbie but I have managed to develop one number crunching app and purposely steered clear of arrays to do it. My coding is naieve to say the least. I dont yet know the shorthand way to code variables and arrays so I end up doing lines of basic looking code for every possible combination of events (haha - the caveman approach to developing!).

    I should have mentioned earlier I was referring to multi select listbox arrays. I have a specific problem. It would take me forever to explain it the way it occurs in my head so it would probably be better for me just to throw the code up, explain the situation and let you see whats happening. This is just a very rough example of what I'm talking about:

    Private Sub Form_Load()
    List1.AddItem ("Item 0")
    List1.AddItem ("Item 1")
    List1.AddItem ("Item 2")
    List1.AddItem ("Item 3")
    List1.AddItem ("Item 4")
    List1.AddItem ("Item 5")
    List1.AddItem ("Item 6")
    List1.AddItem ("Item 7")
    End Sub

    Private Sub List1_Click()
    Dim intLoopIndex
    For intLoopIndex = 0 To List1.ListCount - 1
    If List1.Selected(intLoopIndex) Then
    List2.AddItem List1.List(intLoopIndex)
    End If
    Next intLoopIndex
    End Sub

    =========================
    I'm trying to move selections from list 1 to list 2, but every time you make a selection, it also remembers the previous selection and re-adds it along with the new one (thus, duplications aplenty). I know I could get around this problem by adding a command button and not doing the calculations for the selections on the fly like I'm trying to, but I really want it to work on the fly without the need for extra button clicks.

    I'm sorry to ask for help in this way, but I've been at this for days. I've come close once or twice to cracking it but its elusive to my caveman like brain!! Every time I go looking for a solution I can find something that dances around the problem, but not this specific problem and its driving me crazy!!!! :D
    I know this is probably a really simple thing.
    3/10/2011 3:03:42 AM

  • pons
    Feel free to ask me any help for learning VB. I am willing to help you if i have enough time to answer.

    I dont have the VB6 versin installed in my machine currently.

    likely your click should like below

    Private Sub List1_Click()

    List2.AddItem List1.SelectedItem
    End Sub

    wait for some time. I will install the visual studio 6 and let me try to help you out.
    3/10/2011 4:10:25 AM

  • pons
    I could not locate my Visual Studio 6 disk. Please let me know if the following worked for you.

    Private Sub List1_Click()
    Dim intLoopIndex
    For intLoopIndex = 0 To List1.ListCount - 1

    If List1.Selected(intLoopIndex) Then
    if(not ItemExists(List1.List(intLoopIndex))

    List2.AddItem List1.List(intLoopIndex)
    end if
    End If

    function ItemExists(ItemToCheck) as boolean

    Dim intLoopIndex
    For intLoopIndex = 0 To List1.ListCount - 1
    if(List1(intLoopIndex )=ItemToCheck) then
    ItemExists = true
    exit function
    end if

    loop

    end function
    Next intLoopIndex
    End Sub

    I have written the code directly here in the comment box. So try to understand and reproduce
    3/10/2011 4:49:46 AM

  • GUEST
    Oh man, please dont go installing things on account of me. It's likely that a lot of problems are going to come up from using an old version (its just occurred to me that there could be big syntax changes between the versions) so I'm just going to upgrade so dont worry about it. 3/10/2011 4:55:56 AM

  • GUEST
    3/10/2011 8:10:00 AM

  • GUEST
    HI THANKS VB
    3/10/2011 8:14:32 AM

  • pons
    I need to have VB6 installed on my machine too. I am having some sample applications on vb6. I reinstalled my machine few weeks back and forgot to install visual studio 6. I misplaced the CD somewhere.

    Take care
    3/10/2011 8:30:49 AM

  • GUEST
    Just seen your reply. Had a quick play around with your code and it does throw up one or two little errors on one line (the line with the If Not argument) but thats cool, I'm going to play around with it and see if I can get it to drop in and then see what it does. I'll get back to you.

    Just wanted to say I really appreciate the help and time you've given to this. By the way, I've installed vb10 express on my machine so I'm going to play with that when I've got this problem hammered. Thanks again. I hope I can be as helpful to you or others when the time comes.

    3/10/2011 9:10:16 PM

  • pons
    I am so happy that my help inspired you to help me and others. Hope to see you shine and help others soon

    Thankyou
    3/10/2011 9:42:06 PM

  • GUEST
    THANKS:- You help me for exam preparation 3/21/2011 5:37:11 AM

  • GUEST
    what a lovely program
    thanks
    but one line is wrong
    it will be
    val(Text1.Text)
    4/6/2011 12:28:29 AM

  • GUEST
    I want to know the codes and a clear explanation on what codes to use and all that but also the other mathematical functons included in the calculator as well.
    4/8/2011 8:34:29 PM

  • GUEST
    very nice code 4/28/2011 8:25:16 PM

  • GUEST
    ho ho thank u friends a have need this type calulater for my project so,it's hep ful thank u. 6/26/2011 6:45:41 AM

  • GUEST
    tenk u !! it will help a lot :))) 7/10/2011 7:34:08 PM

  • GUEST
    thanks for the code.
    7/11/2011 1:44:18 AM

  • GUEST
    thanx a lot!!!!!!!!!!!! 7/11/2011 2:24:24 AM

  • GUEST
    please help me.
    I want to make a contact book in visual basic6. In that program all the entry should be stored in Microsoft access 2007. This must have a options like save,edit,delete,first,last.

    SAVE = SAVE THE ENTRY
    EDIT = EDIT THE OPENED ENTRY AND SAVES IT
    DELETE = DELETE THE OPENED ENTRY
    FIRST = JUMP TO THE FIRST ENTRY
    LAST = JUMP TO THE LAST ENTRY


    thank you
    waiting for your quick and positive reply.....

    my mail id is : ruchitmewada@gmail.com
    7/15/2011 2:23:38 AM

  • GUEST
    THANX...
    8/12/2011 3:42:41 AM

  • GUEST
    THANX...
    8/12/2011 3:42:44 AM

  • GUEST
    thank you 8/13/2011 5:13:36 AM

  • GUEST
    thank you 8/17/2011 12:31:57 AM

  • GUEST
    8/23/2011 1:30:06 AM

  • GUEST
    how to get the some of the 1+1+1+?
    pls! help me guys,............pls!!!!!!!
    8/23/2011 3:48:23 AM

  • pons
    Ok to get 1+1+1

    You need to change the code a bit.
    Change the event code cmdEquals_Click to a function
    in the cmdOperator_Click event call this new function and assign the function output to FirstPart variable.

    I dont have the Vb6 installed in my machine. Try to write the code yourself based on the above.

    8/23/2011 4:42:48 AM

  • GUEST
    Poop 8/29/2011 4:35:09 PM

  • GUEST
    AddDigits (Chr(KeyCode - 48))
    explain me
    8/29/2011 9:54:03 PM

  • GUEST
    i want to get all the code of the C calculator
    9/2/2011 11:08:34 AM

  • GUEST
    hi to all!i have some problems about my project vb.some command are running except one, the equal command.how can i code this command..that's my one problem i ever had right now..please help me.
    thanks!!
    God bless
    9/15/2011 11:07:51 PM

  • GUEST
    9/24/2011 10:54:58 AM

  • GUEST
    it is usefull 9/26/2011 9:27:28 AM

  • GUEST
    wow............................. it is useful thanks 9/29/2011 10:48:44 PM

  • GUEST
    thanks alot maam/sir
    i hope to pass my subject comp11
    mr.'stirring-rod'
    10/13/2011 6:16:24 AM

  • GUEST
    E2 VB 8
    Public Class Form1
    'Holds which operation to perform.
    Dim operand1 As Decimal
    'Holds which operation to perform.
    Dim operand2 As Decimal
    Dim ope As Char
    Dim isOpe As Boolean
    'Holds whether the remaining values in the
    'textbox is the calculated values or not.
    Dim calculated As Boolean = False
    Dim memoryRecall As Decimal
    Dim memorysave As Decimal

    Private Sub Button17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click, Button3.Click, Button2.Click, Button18.Click, Button17.Click, Button16.Click, Button12.Click, Button11.Click, Button10.Click, Button1.Click
    If isOpe = True Then
    txtDisplay.Clear()
    isOpe = False
    End If
    txtDisplay.Text &= CType(sender, Button).Text
    End Sub

    Private Sub Button15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button9.Click, Button7.Click, Button6.Click, Button15.Click, Button14.Click, Button19.Click
    isOpe = True
    ope = CType(sender, Button).Text
    operand1 = txtDisplay.Text

    End Sub

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
    'First make sure memory contains something to calculate.
    If txtDisplay.Text = Nothing OrElse txtDisplay.Text = "" Then Exit Sub
    operand2 = txtDisplay.Text

    If ope = "+" Then
    'adding first operand to 2nd operand.
    txtDisplay.Text = CDec(operand1) + CDec(operand2)
    End If
    If ope = "-" Then
    txtDisplay.Text = CDec(operand1) - CDec(operand2)
    End If
    If ope = "*" Then
    txtDisplay.Text = CDec(operand1) * CDec(operand2)
    End If
    If ope = "/" Then
    txtDisplay.Text = CDec(operand1) / CDec(operand2)
    End If
    'hmm. my % value is fixed at 100%, haha
    If ope = "%" Then
    txtDisplay.Text = CDec(txtDisplay.Text) / CDec(100) * operand1
    End If
    'getting the square root of the nubmers
    If ope = "v" Then
    txtDisplay.Text = Math.Sqrt(operand2)
    End If

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button21.Click
    txtDisplay.Clear()
    End Sub

    Private Sub Button23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button23.Click
    txtDisplay = Nothing

    End Sub

    Private Sub Button28_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button28.Click
    txtDisplay.Paste()

    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
    If txtDisplay.Text.Contains(".") Then
    Exit Sub
    Else
    txtDisplay.AppendText(".")
    End If
    End Sub

    Private Sub Button26_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button26.Click

    End Sub

    Private Sub Button20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button20.Click
    'These codes will convert a Signed number to a Unsigned number and vice-versa.
    Dim txtValue As Decimal

    'txtValue decimal variable created above.
    If Decimal.TryParse(txtDisplay.Text, txtValue) Then
    'If "-1" is returned then its a negative number. If it returns 1, then its a positive
    'number
    If Math.Sign(txtValue) = "-1" Then
    ' to convert a value to a positive number :)
    txtDisplay.Text = Math.Abs(txtValue)
    'math.absolute value.= getting the real numbers in short
    'only positive integers will be accepted
    Else
    ' to convert a value to a negative number :)
    txtDisplay.Text = -txtDisplay.Text

    End If

    End If
    End Sub

    Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
    'decimal tryparse , to overload but specify the invalid value.
    If Decimal.TryParse(txtDisplay.Text, vbNullString) Then

    txtDisplay.Text = 1 / (CDec(txtDisplay.Text))
    'Update to True since you should have just calculated the values.
    calculated = True

    End If
    End Sub

    Private Sub Button27_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button27.Click
    txtDisplay.Text = Nothing

    End Sub

    Private Sub Button25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button25.Click

    End Sub

    Private Sub Button24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button24.Click

    End Sub

    Private Sub Button22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button22.Click
    'Keep removing digits one at a time until there are no more left.
    '
    If txtDisplay.TextLength = 0 Then

    Exit Sub

    Else
    'removing digits by 1 starting from right.
    txtDisplay.Text = txtDisplay.Text.Remove(txtDisplay.TextLength - 1)

    End If
    End Sub
    End Class
    11/21/2011 6:21:25 PM

  • GUEST
    12/3/2011 2:14:46 AM

  • GUEST
    thank you very much by k.kamalakannan 1/7/2012 1:04:44 AM

  • GUEST
    tang ina mu mali naman 1/11/2012 9:15:42 PM

  • GUEST
    there's someething wrong in your code..try to check it








































    2/7/2012 8:47:20 PM

  • GUEST
    I mean a plain and clear example on how to wite codes in vb for calculator 2/21/2012 6:32:31 AM

  • GUEST
    pls help me... i need a code for a scientific calculator.. tnx... 2/29/2012 6:00:29 AM

  • GUEST
    thanks....................... 3/3/2012 11:54:48 AM

  • GUEST
    thank you 3/30/2012 9:40:29 AM

  • GUEST
    thnx...it works...:)
    7/17/2012 11:37:56 AM

  • GUEST
    please some one explain me CONTROL ARRAY as easily as possible..kelly 7/17/2012 11:40:30 AM

  • GUEST
    plz explian control array 7/22/2012 3:07:28 PM

  • GUEST
    thanx

    joseph5656@rediffmail.com on fb
    10/12/2012 6:34:14 AM

  • GUEST
    this did not help!!!!!! :( 10/30/2012 1:25:52 PM

  • GUEST
    good afternoon please give me a code of simple calcultor. 12/11/2012 11:49:54 PM

  • GUEST
    please help me to make a simple calculator in vb6. 12/11/2012 11:56:03 PM


Comments
   
Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    



Spam Bot Trap



   



Select Theme
White
Blue
Brown
Gray