Axel8017
Axel8017

Reputation: 31

Visual Basic - System.IndexOutOfRangeException

So my part of the code that gives me problems is this one. It says:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication1.exe

Additional information: Index was outside the bounds of the array

for Label1.Text = question(i - 1,0) and I really don't understand.

I am at the start and I am really trying to learn things for programming.

Public Class Test1
Dim question(2, 5) As String
Dim i As Integer = 2
Private Sub Test1_Load()
    question(1, 0) = "2+2="
    question(1, 1) = "1"
    question(1, 2) = "2"
    question(1, 3) = "3"
    question(1, 4) = "4"
    question(2, 0) = "How old are you?"
    question(2, 1) = "12"
    question(2, 2) = "13"
    question(2, 3) = "17"
    question(2, 4) = "18"
    Label1.Text = question(i - 1, 0)
    nr1.Text = question(i - 1, 1)
    nr2.Text = question(i - 1, 2)
    nr3.Text = question(i - 1, 3)
    nr4.Text = question(i - 1, 4)

End Sub

Upvotes: 1

Views: 1333

Answers (1)

obl
obl

Reputation: 1799

Your code didn't give me any errors on dotnetfiddle.net. So "question" is a 2D array indexed from 0-2 and 0-5. Here's what it kinda looks like:

   0   1   2   3   4   5
0  s   s   s   s   s   s
1  s   s   s   s   s   s
2  s   s   s   s   s   s

Where each 's' represents a string. So if you're accessing question(0, 0), then it would be the 's' in the top left. If you're accessing question(0, 1), then it would be the 's' to the right of that one. If you try to access something outside of the bounds of your array, you will get an error, for example, if you try to access question(3, 0).

So to fix your error, you need to figure out what the value of i is. Try putting

MessageBox.Show(i)

right before the line that's giving you the error.

Upvotes: 1

Related Questions