Objectives of the Week
Case Structure
A Case Structure is very similar to a nested if statement. It is specifically used when you need to compare the contents of a variable to a finite list of conditions. In Visual Basic, the Case Structure is implemented using the Select - Case syntax.
The Select Case structure works with a single test expression that is evaluated one time at the top of the structure. The expression is compared to the values for each Case in the structure. If there is a match, the block of statements associated with that Case is executed
Select Case expression
Case constant list
Statement or Block of Statements
Case constant list
Statement or Block of Statements
Case Else
Statement or Block of Statements
End Select
If more than one Case matches the test expression, only the instructions associated with the first match will be executed.
Here are some examples of the constant list syntax
Case Is | Range | Case Is >= 100 |
Case x To y | Between Inclusive | Case 80 To 90 |
Case "Test" | Match | Case 10 |
Case a, b, c | In the List | Case 20, 30, 40 |
Private Sub cmdTest_Click()
Dim intNumber As Integer
Dim strMsg As String
intGrade = Val(txtNumber.Text)
Select Case intGrade
Case 10, 20, 30
' In the List
strMsg = "10, 20,
or 30"
Case 40 To 50
' Between the numbers (Inclusive)
strMsg = "40 to
50"
Case Is > 60
' Range Check
strMsg = ">
60"
Case Else
' Catch everything else
strMsg =
"Else"
End Select
MsgBox strMsg
End Sub
As in prior examples, when making comparisons on string variables, it's a good idea
to use the UCase on the Select Case expression, and the code the constant list using upper
case strings.
Arrays
An array is an ordered collection of data contained in a variable and referenced by a single variable name. Each element of the array can be referenced by a numeric subscript.
We think of the array as a list of elements. The number of elements are specified when the array is declared. In Visual Basic, the arrays are zero based (just like List and Combo Boxes).
Dim Array(5) as Integer Array of 5 integers. Each Index 0 - 4 Just like List and Combo Boxes
Dim Array (-5 to 5) as Integer 11 Slots - Used when Index Values "Map" to a range
Attempting to reference an element outside the range will result in:
Programs can be built using function calls to determine the array boundaries. UBound and LBound returns the largest and smallest available subscripts of an array.
Private Sub cmdTest_Click()
Dim iArray(-5 To 5) As Integer
Debug.Print "Lower Bound is : " & _
LBound(iArray) & _
". Upper Bound is " & _
UBound(iArray)
End Sub
Results in:
Lower Bound is : -5. Upper Bound is 5
The For Next Loop is often ideal for array processing as they are fixed in size. Review the following example that will search an array for a value and if the value is not found, then the value will be added to the array. The Boolean value and the Exit For instruction are key to the search logic.
Dim intArray(10) As Integer
Private Sub cmdFind_Click()
Dim i As Integer
Dim blnFound As Boolean
Dim intSearch As Integer
blnFound = False
intSearch = Val(txtSearch.Text)
For i = 0 To 9
If intArray(i) = intSearch Then
blnFound = True
Exit For
End If
' An element containing zero indicates
' the end of the list
If intArray(i) = 0 Then
Exit For
End If
Next i
If blnFound = False Then
intArray(i) = intSearch
Debug.Print "Added in slot " & i
Else
Debug.Print "Found in slot " & i
End If
End Sub
Dynamic Arrays
Fixed sized arrays work in many situations, but because the size is static, the possibility (or probability) exists that they will at some point in the future be too small to hold the required information. Visual Basic allows the array dimensions to be dynamic. To declare a dynamic array, an array size is not specified.
Dim intArray() As Integer
To allocate space to the array, use the ReDim instruction.
ReDim intArray(1)
It is the responsibility of the programmer to manage the content and the size of a dynamic array.
ReDim Preserve intArray(10)
Adding the Preserve keyword will leave the current array contents in tact.
Compare this example of adding to an array to the previous example. This example will maintain the size of the array based on the number of entries required. The first example had a fixed sized array, and with that, the possibility of overflowing the bounds of the array. The changes to the code are highlighted.
Dim intArray() As Integer
Dim gintCount As Integer
Private Sub cmdFind_Click()
Dim i As Integer
Dim blnFound As Boolean
Dim intSearch As Integer
blnFound = False
intSearch = Val(txtSearch.Text)
If gintCount = 0 Then
' Needed because UBound fails
ReDim intArray(1)
' on an empty array
End If
For i = 0 To UBound(intArray)
If intArray(i) = intSearch Then
blnFound = True
Exit For
End If
' An element containing zero indicates
' the end of the list
If intArray(i) = 0 Then
Exit For
End If
Next i
If blnFound = False Then
gintCount =
gintCount + 1
ReDim Preserve intArray(gintCount)
intArray(i) = intSearch
Debug.Print "Added in slot " & i
Else
Debug.Print "Found in slot " & i
End If
End Sub
This section was a basic review of how to process arrays. This chapter will use
arrays in conjunction with List and Combo Boxes, and User Defined Types, which are
described later in the chapter
Multidimensional Arrays
A multidimensional array is an array that looks like a table. It has more than one index specified when it is declared.
Dim sngRateTable(5, 4) As Single
This statement creates an array of 20 elements indexed as indicated.
|
Nested For Loops are often used to address each array element For i = 0 to 4 This example will initialize each element of the array to zero. |
See Page 300 of the Text for a good example of a Lookup procedure that will search for a particular value in a table or refer to the Search and Add examples above.
Control Arrays
A control array is exactly what it says it is. It is an array of controls on a form. A control array is always made up of the same type of control. That is to say, you can not have a control array that is made up of a mix of TextBoxes and OptionButtons.
Each element in the array has its own properties, but the event handlers are shared between all elements of the array. The difference between the event handlers in a control array is that an Index parameter is passed indicating which control in the array is being handled. You need to be sure that when you create a control array that you can share the event handlers.
Control arrays can be created several ways:
When using these methods, you will be prompted with a dialog box warning you that you are about to create a Control Array
You can also:
In order to create a control array at runtime, at least one element has to have been placed on the form at design time, and set the Index property set to 0. To create further instances of the control at runtime, use the Load instruction. Your runtime logic must also reposition the array by changing the form location properties such as Top and Left, and you must set the Visible property to True.
Here is an example that will use a Control Array of Option Buttons to change the Background Color of the Form Controls.
Private Sub optColor_Click(Index As Integer)
Select Case Index
Case 0
Me.BackColor = vbRed
Case 1
Me.BackColor = vbGreen
Case 2
Me.BackColor = vbBlue
Case Else
MsgBox "Error Detected", vbOKOnly +
vbCritical, "Error Message Alert"
End Select
Dim i As Integer
For i = 0 To 2
optColor(i).BackColor = Me.BackColor
Next i
End Sub
Clicking on any one of the Option Buttons will trigger the Event Handler passing the Index Value of the control that was clicked. Using the Case Structure, the Index value can be determined and the color changed as was requested. The For Loop at the bottom will set the Background color of each of the Option Buttons.
The alternative is to code three event handlers.
Tag Property
The TAG property provides temporary storage space that can be associated with a particular control. You can do most anything you want with this space. The example below is a modification to the Color Selection program that uses the Tag property instead of the Case Structure.
In Form Load, initialize the Tag for each element in the control array
Private Sub Form_Load()
optColor(0).Tag = vbRed
optColor(1).Tag = vbGreen
optColor(2).Tag = vbBlue
End Sub
The click event can then reference the appropriate TAG property based on the index.
Private Sub optColor_Click(Index As Integer)
Me.BackColor = optColor(Index).Tag
Dim i As Integer
For i = 0 To 2
optColor(i).BackColor = Me.BackColor
Next i
End Sub
The Tag property is available with any VB control, not just Control Arrays
UDT - User Defined Type
VB's user-defined type (UDT) allows you to build data structure that
consists of the intrinsic data types or other user-defined types.
Here is an example:
Type udtItem
intKey as Integer
strDescription as String
sngCost as Single
End Type
After defining the UDT, you can now declare variables of this new type just as you would a string or an integer.
The UDT does not define a
variable.
It only defines a type that can be used to declare a variable.
To declare a variable of this type:
Dim udtVariable As udtItem
Now I can reference the fields with the UDT using the Object.Property notation.
udtVariable.intKey = 0
udtVariable.strDescription = "A New Product"
MsgBox "The cost is " & udtVariable.sngCost
Here are some of the many ways that you can declare and then access the components of a UDT
Type udtPerson strFirst As String strLast As String End Type |
Type udtPosition strTitle as String sngSalary As Single End Type |
Type udtStaff udtEmployee As udtPerson udtHistory (10) As udtPosition End Type |
Dim udtDirector as udtStaff |
udtDirector.udtHistory(i).strTitle |
Dim udtVPs(5) as udtStaff | udtVPs(j).udtEmployee.strLast = "Smith" udtVPs(j).udtHistory(i).strATitle = "VP" |
Dim udtStudent as udtPerson | udtStudent.strFirst = "Bob" |
Note that you ALWAYS make reference to the declared variable and NEVER to the type
List Boxes and Arrays
There can be a direct relationship between the content of a ListBox and the content of an array. Both are subscripted, so the ListIndex property can be used to access the associated entry in the array.
As each element is added to the ListBox, the associated information is added to the Array. The AddItem method of the ListBox will place the new ListBox entry at the end, and the ListCount property (actually ListCount - 1) will point to the associated array element as indicated in the diagram
The Sorted Property changes the direct relationship, but VB provides the means to keep this association using the ItemData and the NewIndex properties.
NewIndex contains the position of the newly added element in the ListBox. Storing
ListCount - 1 in this entries ItemData property maintains the relationship with the array.
The ItemData property is used to store a numeric (long) value in either a ListBox or
ComboBox. The ItemData property is similar to the Tag property, but ItemData seems
especially suited to handle an index into an array that will hold associated data.
When the Sorted property is set to True, Visual Basic will maintain the order of the ListBox array and the direct relationship is broken. But using ItemData and NewIndex Properties, this relationship can easily be maintained.
ListBox.AddItem txtBox.Text | Add an entry to the ListBox: |
ListBox.ItemData(ListBox.NewIndex) = ListBox.ListCount - 1 | Places in the ItemData Property of the Newly Added ListBox entry, the associated Array element as is maintained by ListCount |
Array(ListBox.ListCount - 1) = Associated Info | Update the Array |
Take a look at this example:
Private Sub Form_Load()
With List1
.AddItem "Tom"
.ItemData(List1.NewIndex) = .ListCount - 1
.AddItem "Dan"
.ItemData(List1.NewIndex) = .ListCount - 1
.AddItem "Linda"
.ItemData(List1.NewIndex) = .ListCount - 1
.AddItem "Jim"
.ItemData(List1.NewIndex) = .ListCount - 1
.AddItem "Cindy"
.ItemData(List1.NewIndex) = .ListCount - 1
.AddItem "Ken"
.ItemData(List1.NewIndex) = .ListCount - 1
End With
End Sub
Private Sub List1_Click()
Dim Msg As String
With List1
Msg = .ItemData(.ListIndex) & vbTab & .List(.ListIndex)
MsgBox Msg
End With
End Sub
This demonstrates that the ItemData property contains the proper Array association
Build the Example
Step by Step through Example 1
Make sure that you:
Another Example
Step by Step through the Example 2
Make sure that you:
Lab 1 -From the Text - Page 324, VB Mail Order
This is a pretty easy exercise demonstrating a lookup function
Step by Step through the First Lab
Let me know when you are done and I will check you off as Complete
Lab 2 - From the Text - Page 324, VB Auto Center
You are on your own.
Reading Assignment
Programming Assignment
As Always: The assignment is due before the start of class next week
Orchestra Tickets
Page 321, Problem 8.3
The ListBox that holds the selection must be sorted. This means that the Sorted Property is set to True. You will need a table that keeps the totals for the different ticket sales and the index into the table must be stored in the ItemData property of the ListBox.