Arrays with constants for subscripts

As we saw in our note on array terminology, arrays are declared using a Dim statement and referenced using the array name with a subscript. The subscript can be any numeric expression, but in this example, we only use constants as subscripts. While that would not make sense in a real application, it will help with learning to use arrays.

The following program lists names stored in an array:

Dim strNames(4) As String  'friend's names

Private Sub btnMen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMen.Click
   strNames(0) = "George Washington"
   strNames(1) = "Abraham Lincoln"
   strNames(2) = "Franklin Roosevelt"
   strNames(3) = "Harry Truman"
   strNames(4) = "John Kennedy"
End Sub

Private Sub btnWomen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWomen.Click
   strNames(0) = "Martha Washington"
   strNames(1) = "Mary Lincoln"
   strNames(2) = "Elanore Roosevelt"
   strNames(3) = "Bess Truman"
   strNames(4) = "Jaqueline Kennedy"
End Sub

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click
   txtOut.Clear()
   txtOut.AppendText(strNames(0) & vbCrLf)
   txtOut.AppendText(strNames(1) & vbCrLf)
   txtOut.AppendText(strNames(2) & vbCrLf)
   txtOut.AppendText(strNames(3) & vbCrLf)
   txtOut.AppendText(strNames(4) & vbCrLf)
End Sub

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click
   strNames(0) = ""
   strNames(1) = ""
   strNames(2) = ""
   strNames(3) = ""
   strNames(4) = ""
End Sub

The program has a five-element array called strNames and event handlers for clicking on four buttons. The first event handler assigns men's names to the array and the second assigns women's names to the array. As you see, we use standard assignment statements, and the subscripts are all numeric constants in this example. The third event handler displays the five names currently assigned to the array, and the fourth event handler clears each array element.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.