Page 183 - Open Soource Technologies 304.indd
P. 183

Unit 7: Arrays in Visual Basic


               Private Sub cmdEqual_Click()
               Select Case Choice
               Case “+”
               Result = Previous + Current
               txtDisplay.Text = Result
               Case “-”
               Result = Previous - Current
               txtDisplay.Text = Result
               Case “*”
               Result = Previous * Current
               txtDisplay.Text = Result
               Case “/”
               Result = Previous / Current
               txtDisplay.Text = Result
               End Select
               Current = Result
               End Sub
               Save and run the project. On clicking digits of user’s choice and an operator button, the output
               appears.
               7.3.1 Iterating on the Items of a Control Array
               Control arrays often let you save many lines of code because you can execute the same statement,
               or group of statements, for every control in the array without having to duplicate the code for
               each distinct control. For example, you can clear the contents of all the items in an array of
               TextBox controls as follows:
               For i = txtFields.LBound To txtFields.UBound
               txtFields(i).Text = “”
               Next
               Here you’re using the LBound and UBound methods exposed by the control array object, which
               is an intermediate object used by Visual Basic to gather all the controls in the array. In general,
               you shouldn’t use this approach to iterate over all the items in the array because if the array has
               holes in the Index sequence an error will be raised. A better way to loop over all the items of
               a control array is using the For Each statement:
               Dim txt As TextBox
               For Each txt In txtFields
               txt.Text = “”
               Next
               A third method exposed by the control array object, Count, returns the number of elements it
               contains. It can be useful on several occasions (for example, when removing all the controls that
               were added dynamically at run time):





                                      LOVELY PROFESSIONAL UNIVERSITY                        177
   178   179   180   181   182   183   184   185   186   187   188