CIS 230, Visual Basic
Ch. 8 Notes, page 1
Objective #1: Set up and use a control array.
- An array is a group of objects with the same name. In this chapter, you
will study two kinds of arrays, control arrays and arrays of
variables.
- A control array is simply a group of VB controls that have the same name. Remember,
controls are objects that you can place on a form that such as command buttons, text
boxes, and labels. In a control array, each control must be of the same class. That is, no
matter how many controls are in a control array, they all have to be the same type of
control, option buttons for example.
- Individual controls within a control array can be referenced by an index
(sometimes called a subscript.) Actually, the whole name of an individual
control in a control array includes the index which is placed in parentheses. The name of
a specific control in a control array of command buttons might be cmdLevel(5)
where 5 is the index.
- All of the controls in a control array share the same Click method (as well as other
methods specific to the type of control.) This allows a programmer to efficiently place
one code segment in the body of the Click event procedure and expect it to execute when
the user clicks on any of the controls in the control array. In some situations, it is not
desirable to have such overlap but in others it is extremely useful.
- Each of the controls in a control array can have unique properties, however. Therefore,
you could make the BackColor of one command button vbGreen and another's vbBlue but still
expect the same code to execute when either one is clicked.
- To create a control array of option buttons for example, you first create an option
button but change its name to optCar(0). That is you type 0 in parentheses after the
actual name of the option button. This causes all subsequent option buttons that are named
optCar to automatically take the names optCar(1), optCar(2), optCar(3), etc. Note that the
first control in a control array always has the index 0.
- You can also create a control array by creating the first control as usual. Then copy
and paste a duplicate of that control on the same form. VB will ask you whether you would
like to create a control array and if you click "Yes", the next control of that
type will take the appropriate name with an index of 1.
Objective #2: Code selection logic using a Select Case statement.
- Generally most nested If statements can be rewritten as a Select Case statement.
Often Select Case is used because it is easier to read and understand.
- The general form of the Select Case statement is:
Select Case expression
Case constant list
statement(s)
[Case constant list]
[statement(s)]
[Case Else]
[statement(s)]
End Select
- Usually the expression in the first line is a variable . Depending on the value of that
variable, the computer will perform the statements in one of the branches under each Case
statements. The constant lists are specific values or ranges of values that the variable
could take on.
- While it is not required, specifying a Case Else is a wise idea since it can be used
effectively for error-checking and validation.
- Once VB matches the expression with one of the constant lists and performs the
statements directly after that constant list, it will transfer control to the first line
of code below the End Select statement.
- The Select Case structure is particularly effective within the Click procedure of a
control array of option buttons. An argument named Index is automatically sent to the
Click event for an option button control array. This argument indicates which option
button was actually clicked by the user (remember the index of the first control in a
control array is zero not one.) See pp. 291 & 292 for a good illustration of how
Select Case is really useful in this situation.
Objective #3: Establish an array of variables and refer to individual elements
in the array with variable subscripts
- In any programming language, one can create an array of variables.
Often arrays of variables are simply called arrays. If you mean to
indicate that something is a control array as opposed to an array of variables, you should
clearly state that it is a "control array."
- An array of variables is a group of variables with the same data type and name except
that it is required to place the index of specific array variable at the end of its name.
If you were writing a teacher's gradebook program for example you may wish to store the
semester's 5 quizzes for a student in an array of variables with specific variables named
StudentQuizzes(0) through StudentQuizzes(4). The only reason index values 0 through 4 are
used instead of 1 through 5 is because VB sets the first array variable to index 0 by
default.
- Using arrays of variables makes it easy to manipulate, search, sort, and perform other
tasks with related variables. For example, to initialize all 5 of a student's quiz scores
to zero at the beginning of a semester, you could use brute force like:
StudentQuizA = 0
StudentQuizB = 0
StudentQuizC = 0
StudentQuizD = 0
StudentQuizE = 0 |
or, you could use a loop and an array: |
For j = 0 To 4
StudentQuizzes(j) = 0
Next j
|
- The actual values that are stored in specific array variables are called elements.
In the example, above zero is an element of all 5 subscript positions of the array
StudentQuizzes.
Objective #4: Use the For Each/Next to traverse the array.
- Traversing an array simply means visiting each position/element of the
array. You could traverse an array in order to search for the occurrence of a specific
value or you could traverse an array in order to subtotal its elements.
- To find a subtotal of the elements of an array, you could use a loop and an accumulator
statement:
For j = 1 To 5
intTotal = intTotal + StudentQuizzes(j)
Next j
- To declare an array, you use a statement like Dim
StudentQuizzes(5) As Integer where the array
StudentQuizzes will be able to hold five elements in with subscripts 0 through 4. If you
prefer to work with subscripts 1 through 5 you can specify that range with a declaration
statement like Dim
StudentQuizzes(1 To 5) As Integer .
- It is possible to create a dynamic array where the total number of
elements in an array is not specified. Otherwise, you are creating a static array
which cannot change its size during a program's execution.
- The For Each/Next loop structure allows you to conveniently traverse an
array. For example, you could initialize each element of the array intExample to a certain
value with the following code:
For j = 1 To 10
intExample(j) = 15
Next j
or, you could use a For Each/Next loop,
Dim vntTemp As Variant
For Each vntTemp In intExample
vntTemp = 15
Next vntTemp
where the variant variable vntTemp is simply used with the loop to traverse the array
intExample and assign each element the value 15. The For Each/Next loop may not seem
particularly more efficient than the For/Next loop but if you need to traverse and
initialize a multidimensional array it is a better choice. Instead of nested
For/Next loops....
For r = 1 to 10
For c = 1 to 10
intExample(r, c) = 15
Next c
Next r
the For Each/Next loop is more efficient...
For Each vntTemp In intExample
vntTemp = 15
Next vntTemp
since the loop does assign every element of the two-dimensional array intExample to the
value of 15.
Objective #5: Create user-defined data types for multiple fields of related
data.
- VB allows you to use a number of simple data types such as Integer, String, Boolean,
Long, etc. Sometimes, it is very useful to use more complicated variable data types. You
can create your own user-defined data types in such situations.
- User-defined data types are used to combine related data into units. For example, it may
be efficient for a gradebook program to have a user-defined data type called Student which
has individual fields for a student's name, Social Security Number, Year
of Graduation, Telephone Number, etc.
- One uses a Type statement to create a user-defined data type in the
general declarations section of a module. If it is used in a form module the keyword
Private must be used before the word Type.
- An example of a Type statement is:
Type Student
strLastName As String
strFirstName As String
strSocSecNumb As String
intYrGraduation As Integer
strTelephoneNumber As String
End Type
This user-defined data type has 5 fields.
- To access information within one of the fields of a user-defined data type, you must use
dot notation. For example, to have the last name of a student placed in a label
named lblExample, you would first have to assume that a variable of data type Student was
declared as in Dim
udtTeachersPet As Student . You would also assume that
the field strLastName of udtTeachersPet contains someone's last name. To have that element
placed in the label, use the statement
lblExample.Caption = udtTeachersPet.strLastName Note that udt
is the common prefix for user-defined data types.
- Often one declares an array of a user-defined data type such as a whole array of
variables of type Student. Such a declaration would look like
Dim
ClassList(30) As udtTeachersPet
and to place the first name of the 5th person in the array ClassList into Label1, use the
code Label1.Caption =
ClassList(4).strFirsName (Note that
the element in the fifth position would have the subscript of 4.)
Objective #6: Accumulate totals using arrays.
- Accumulator statements such as
intTotal = intTotal + intNextAmount are often used to compute
totals. Arrays can easily be used with accumulator statements since arrays are groups of
variables that can be added and subtotaled.
- It is easy to obtain the total sum of the elements within an array with code like,
intTotal = 0
For j = 1 To 10
intTotal = intTotal + intMyArray(j)
Next j
Simply use the loop variable j to reference each element in the array, intMyArray
- An even more complicated accumulation of many totals can be achieved using an array of
variables. Suppose that the array intNFLTeamWins is used to hold the number of wins for
each NFL football team and that the array has 31 elements indexed from 1 to 31.
Furthermore, suppose that the user enters the index number referring to a specific team in
the text box txtTeam along with that team's number of wins into a text box named txtWins.
To accumulate the updated number of wins for that team the statement
intNFLTeamWins(Val(txtTeam.Text))
= Val(txtWins) can be used. Using the team number as an
index to the array intNFLTeamWins is a technique called direct reference.
Objective #7: Distinguish between direct access and indirect access of a table.
- When a specific element of a table must be modified, you simply need to refer to its row
and column subscripts. For example, to add the value 5 to the item in the second row and
third column of a table, the statement
intExample(1,
2) = intExample(1, 2) + 5 would work.
Note that the element intExample(1,2) is
found in the second row because the row
numbers begin with zero. This technique uses direct access to a table
since the actual subscripts are being used.
- On the other hand suppose that you do not know the actual subscripts of the element in
an array that you wish to modify. In this case you must use a table lookup.
Suppose a user data type Team and an array of Team's named udtNFLTeams exists. Each
udtNFLTeam element contains two fields, strName and intWins. If a programmer wants to
update the number of new wins (intNewWins) for a specific team, he/she must first
determine the index of that team in the array udtNFLTeams. By performing a table lookup,
you can update the intWins field of the appropriate element of the array. You could ask
the user to enter the name of the team and compare this user input with the strName field
of each udtNFLTeams array element. Use a loop from 0 to n - 1 where n is the number of
elements in the array. If the loop variable is j then the statement would look like this:
If txtUserInput = udtNFLTeams(j).strName Then udtNFLTeams(j).intWins = _
udtNFLTeams(j) +
intNewWins
This method of accessing an element of an array without first knowing the element's
subscript or index is considered indirect access.
Objective #8: Combine the advantages of list box controls with arrays.
- The ListIndex property of a list box or combo box allows a programmer
to determine which item is selected by the user. Even though the values in the list box
may not be numeric, the ListIndex property will be a number between 0 and n, where n is
the number of total list box items minus 1. With the ListIndex property you can directly
reference an element of an array in order to, say, add it to a running total.
Objective #9: Coordinate lists and arrays using the ItemData property.
- One problem that could occur when you are working with list boxes and arrays is that the
original elements of a list box could be sorted (using the list box's Sorted property).
When the list box items are sorted, the ListIndex of each element is probably going to be
different from its original ListIndex. Using the technique described in objective #8 would
not work correctly in this case.
- The ItemData property can be used to associate a specific number with
each element of a list box or combo box. The ItemData property for each element will not
change when the list box is sorted. Use the ItemData property just as you would the
ListIndex property in this case.
- You can also use the ItemData property to assign specific values with each element of a
list box if you do not want to refer to the items as having positions (ListIndex
properties) running from 0 to n-1 (where n is the number of total items.)
- If you choose to use the AddItem method to add a new list box item
during runtime, the new item will be added to the end of the list box. The ListIndex
property of the new item would be the next available index number not already assigned.
The ItemData property for the new item however must be specifically assigned. If the list
box was already sorted though, AddItem adds a new item to the appropriate sorted position.
In this case the ItemData property of the new item is determined by Visual Basic and
stored in the list boxes' NewIndex property. You can reference the
NewIndex property until AddItem is used again.
Objective #10: Store data in multidimensional arrays.
- If the data that you would like to store can be conveniently arranged in rows and
columns like spreadsheet data, then you should use a two-dimensional array.
A two-dimensional array (called a table or a matrix) uses two subscripts
to identify each element. The subscripts are usually referred to as the row and the
column.
- An element in a two-dimensional array is referred to with notation like Name(3,4) where
3 refers to the row of the element and 4 refers to the column.
- Example:
13 |
54 |
0 |
29 |
18 |
48 |
71 |
1 |
82 |
46 |
If you wish to refer to the element 29 in the two-dimensional table, Demo, above, you
must use the reference Demo(0,3).
Remember that the first row is row 0 and that the first column is column 0. If you wish to
refer to the 13, you refer to Demo(0,0). I always remember the soft drink RC Cola to
remember which subscript comes first, row or column.
- Any sized multi-dimensional array can be used in VB. Therefore the
array could use more than two subscripts to reference each element. However,
multi-dimensional arrays greater with more than 2 dimensions are rarely used.
CIS 230 Home Page | Mr. Minich's Education Home Page | Minich.com Web Design