Page 313 - Open Soource Technologies 304.indd
P. 313
Unit 14: Building Small Application
Create a subroutine that will handle the clicking of any of the number buttons. We create this
as a subroutine 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
sLeft = sLeft + sNumber
tbResult.Text = sLeft
Else
sRight = sRight + sNumber
tbResult.Text = sRight
End If
End Sub
As we can see, this function takes a string parameter, sNumber, 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, sLeft, and the textbox, tbResult, is updated to display the new number.
If bLeft is false, the same operation is performed using sRight instead.
Finally, create a Click event function for each number that calls our AddNumber subroutine. We
can do this easily by double-clicking each number button, which will create the subroutine
structure. Then add the call to AddNumber, replacing the number in quotes with the number
associated with the button for the zero button, code will look like this:
Private Sub btn0_Click()
AddNumber (“0”)
End Sub
Likewise, for the one button, code will look like this
Private Sub btn1_Click()
AddNumber (“1”)
End Sub
8: Handle the operators: plus, minus, times, and divide. We will do this like last 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
sOperator = sNewOperator
bLeft = False
Else
btnEquals_Click
LOVELY PROFESSIONAL UNIVERSITY 307