We have previously used numeric constants for subscripts, but recall that a subscript can be any integer expression. The following program initializes the array using constant subscripts when the form is first loaded. It displays any element the user requests using a variable subscript.
Dim strNames(9) As String Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load strNames(0) = "George Washington" strNames(1) = "Martha Washington" strNames(2) = "Abraham Lincoln" strNames(3) = "Mary Lincoln" strNames(4) = "John F. Kennedy" strNames(5) = "Jacqueline Kennedy" strNames(6) = "Dwight D. Eisenhower" strNames(7) = "Mamie Eisenhower" strNames(8) = "Harry Truman" strNames(9) = "Bess Truman" End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim ss As Integer ss = CInt(txtSS.Text) lblOut.Text = strNames(ss) End Sub
The user types a number into the TextBox called txtSS. That value is used as the subscript, and the corresponding array element is displayed in the label lblOut.
In this example, we have used a numeric variable for the subscript, but, as you might have guessed, any integer expression can be used as a subscript:
<array name>(<integer expression>)
Note that the program does not check input validity. If the user enters a value outside the range of allowable subscripts, the program fails.