Dynamic Arrays (continued)
Home > Courses > Basic Programming > Arrays > Dynamic Arrays (continued)
Class Exercise: Class List
We will make a program that allows the user to display and search several different class lists.
- Begin by designing the form.
- Use the names
lstStudents, lblCount, cmdFirstGrade, cmdSecondGrade, txtFind, cmdFind, cmdDone
for the controls on the form.
- Add code to
cmdDone
.
- Add a global array variable named
strStudents()
.
- Add code to
cmdFirstGrade
and cmdSecondGrade
to redimension the array and set the names of the students. Finally, call a subroutine named DisplayList
.
- Create a subroutine named
DisplayList
that uses a For…Next loop to display the names of the students in the array.
- Add code to
cmdFind
that searches the currently displayed class list for any whole or partial matches (not case sensitive).
Class List Code |
' global variables
Dim strStudents() As String
Private Sub cmdDone_Click()
‘ end program
Unload frmMain
End Sub
Private Sub cmdFirstGrade_Click()
‘ resize array
ReDim strStudents(1 To 7)
‘ save student names
strStudents(1) = “Doc”
strStudents(2) = “Grumpy”
strStudents(3) = “Sneezy”
strStudents(4) = “Happy”
strStudents(5) = “Sleepy”
strStudents(6) = “Bashful”
strStudents(7) = “Dopey”
‘ display
Call DisplayList
End Sub
Private Sub cmdSecondGrade_Click()
‘ resize array
ReDim strStudents(1 To 4)
‘ save student names
strStudents(1) = “John”
strStudents(2) = “Paul”
strStudents(3) = “George”
strStudents(4) = “Ringo”
‘ display
Call DisplayList
End Sub
Sub DisplayList()
‘ ********************************************************
‘ ** Display student list
‘ ********************************************************
‘ dimension
Dim intCount As Integer
‘ clear list box
lstStudents.Clear
‘ display items
For intCount = 1 To UBound(strStudents)
Call lstStudents.AddItem(strStudents(intCount))
Next intCount
‘ display count
lblCount.Caption = CStr(lstStudents.ListCount) & ” students”
End Sub
Private Sub cmdFind_Click()
‘ dimension
Dim strFind As String
Dim intSearchPos As Integer
Dim blnFound As Boolean
‘ initialize
strFind = txtFind.Text
intSearchPos = 1
‘ linear search loop
Do Until intSearchPos > UBound(strStudents) Or blnFound
If InStr(UCase(strStudents(intSearchPos)), UCase(strFind)) Then
‘ found it!
Call MsgBox(“Found student: ” & strStudents(intSearchPos), _
vbInformation)
blnFound = True
End If
‘ next student
intSearchPos = intSearchPos + 1
Loop
End Sub |