Wyo VB Lecture Notes
Objective #1: Use an array to store data.
- An array (also
called a vector or a list) is a set of related variables.
In fact, all of the variables in the array are referenced by the same name
(the name of the array itself). For example,
if you wanted
to
store
John Doe's five exam grades, it would be more efficient to use an array
instead of 5 separate variables.
Instead of declaring 5 variables with the statement
Dim mintScore1 As Integer = 0
Dim mintScore2 As Integer = 0
Dim mintScore3 As Integer = 0
Dim mintScore4 As Integer = 0
Dim mintScore5 As Integer = 0
You should declare an array named mintScores with the statement
Dim mintScores(5) As Integer
Notice that the name of the array mintScores is plural rather than the singular form.
-
This statement creates one array that has six positions.
Each position of the array can store a separate exam value. The length of the array mintScores is said
to be 6 simply because that is how many elements it can hold. This
array
has
6 elements not 5 because Visual Basic always includes an element with
position (subscript) zero. It is a little confusing but because Visual Basic numbers the rows from 0 to 4, there are a total of 5 rows. Other computer languages also provide a zero column and a zero row but they usually require that you place the actual number of desired elements in the parentheses of the declaration statement.
-
You can declare arrays to be as big as you would like in Visual Basic.
- The values in an array are called elements. The 2 in the statement intExam(2) = 94 is called a subscript or index position.
- While arrays can be declared as local variables within a method, it is usually more efficient to declare an array at the top of the form. When you declare any variable at the top of the form, the variable is called a module-level variable rather than a local variable.
- An array can initialized within its declaration statement by include the initial
values in a set of curly braces. In this case, you must let the parentheses empty. Here is an example:
Dim mintScores() As Integer = {77, 90, 73, 80, 91}
- After you have declared an array, you can display any element of the array. The statement
lblOutput.Text = mintScores(2)
would cause the number 73 to be displayed in the label lblOutput. Note that the 73 is in subscript position 2 even though it is the third value.
The statements
intPosition = 5
MessageBox.Show(mintScores(intPosition))
would cause the value 77 to be displayed in a message box since the variable intPosition is 0 and the value 77 is in subscript position of the array.
- You can change a value stored in an array by using this notation. The statement
mintScores(1) = 99
would overwrite the 90 with a 99 since 90 is in subscript position 1.
- Arrays are useful because they make it easier to program with loops. They organize data so that it can be manipulated and processed more efficiently. For example, instead of five separate statements that initialize each of John Doe's scores to 100 as in:
mintScore1 = 100
mintScore2 = 100
mintScore3 = 100
mintScore4 = 100
mintScore5 = 100
It is easier to initialize them with a For loop as in:
For
J = 1 To 5
mintScores(J) = 100
Next
- The length of an array can be determined by using the Length method.
The following example shows how the length of an array can be used as the
upper
bound of a For loop
For J = 0 To mintExamScores.Length() - 1
MessageBox.Show(mintExamScores(J))
Next
- Here is a code segment that computes the running
total of the elements in an array
Dim intScores() As Integer = {73, 77, 82, 71, 98}
Dim intSum As Integer = 0
Dim J As Integer = 0
For J = 0 To intScores.Length() - 1
intSum = intSum + intScores(J)
Next
Notice that you must start the loop variable J at 0 since the first subscript position of the array is position zero and you must stop J at
the length of the array minus 1
- In addition to storing integers in an array, you can declare an array to store strings or any other variable data type as in
Dim mstrNames() As String = {"Alfred", "Betty", "Chris", "Donna", "Edgar"}
However, you can not store two different data types in the same array. That is you cannot mix integers and strings.
You will not be tested on the information below.
Objective #2: Use Array library methods.
- The Clear method allows you to set one or more of the elements of an array of integers to zero. For example,
Array.Clear(mintExamScores, 0, 4)
would set all of the elements from index position 0 to index position 4 equal to zero.
- The Reverse method reverses the elements in an array. It is used like this Array.Reverse(mintExamScores)
- The BinarySearch method searches an array for a value and returns the index position where the value is found. For example,
Dim intExam() As Integer = {77, 90, 73, 80, 91}
MessageBox.Show(Array.BinarySearch(intExam, 90)
causes the value 1 to display in the message box since the value 90 is found in index position 1 of the array.
- The Sort method sorts an array. The following statement rearranges the elements in mintExamScores so they are in ascending order:
Array.Sort(mintExamScores)
Objective #3 - Create arrays of objects.
- Previously we learned how to create arrays of Integer's, Double's, and String's.
We also previously learned how to make an object (e.g. textbox, label, button, picturebox, etc) using code and without double-clicking the VB Toolbox. Well, we can put all of this together to create
an array of one kind of object using code. For example, you can create 10 or more "alien" pictureboxes and place them on the screen avoiding the need to create them individually using the
mouse. Why would you want to do this? For one, you have more flexibility and control when creating objects with code. Also, it would be very tedious and time consuming to create and edit 30 "alien" picture
boxes when you could use a loop in your computer program do the same thing.
- To declare an array of picture boxes you would use the statement
Dim picFrankenstein(5) As New PictureBox
If you want the array to be module-level, you would use the statement
Dim picFrankenstein(5) As PictureBox
without using the keyword New. Then in the Form_Load method perhaps, you would use the code
For J = 0 To 5
picFrankenstein(J) = New PictureBox
picFrankenstein(J).Image = Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory() + "..\..\images\frankenstein.jpg")
picFrankenstein(J).SizeMode = PictureBoxSizeMode.AutoSize
picFrankenstein(J).Left = Rnd() * 300
picFrankenstein(J).Top = Rnd() * 300
Me.Controls.Add(picFrankenstein(J))
Next
The Me.Controls.Add method must be used to actually place each new picture box onto the current form.
Objective #4: Use ArrayLists.
- An ArrayList is similar to an array. It can also store multiple items and is primarily used when you need to store objects rather than numbers. To declare an
ArrayList, you use
Dim list As New ArrayList
In a Form1_KeyDown method, you could use something like
If e.KeyCode = Keys.Space Then
Dim next As New Label
next.Top = 50
next.Height = 50
Me.Controls.Add(next)
list.Add(next)
You can also use a For Each loop such as
For Each temp in Me.list
Label.Top += 5
Next
and
For Each control in Me.Controls
If (TypeOF(control) Is Label) Then
control.Top += 5
End If
Next
- The following code segment demonstrates how an ArrayList of PictureBoxes can be used to shoot many bullets
Dim picBullets As New ArrayList
Dim intNumBullets As Integer = 0
Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If (e.KeyCode = Keys.Space) Then
picBullets.Add(New PictureBox())
picBullets(intNumBullets).BackColor = Color.Black
picBullets(intNumBullets).Left = 150
picBullets(intNumBullets).Top = 200
picBullets(intNumBullets).Width = 3
picBullets(intNumBullets).Height = 5
Me.Controls.Add(picBullets(intNumBullets))
intNumBullets += 1
End If
End Sub
Private Sub tmrBullets_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrBullets.Tick
For J = 0 To picBullets.Count - 1
If (Not (picBullets(J) Is Nothing)) Then
picBullets(J).Top -= 5
If (picBullets(J).Top <= 0) Then
Me.Controls.Remove(picBullets(J))
picBullets(J) = Nothing
End If
End If
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
picBullets = New ArrayList()
End Sub
- The Count property of an ArrayList keeps track of how many elements are in the ArrayList.