VB GradeBook程序出现System.IndexOutOfRangeException错误求助
First, let's break down what this error means: System.IndexOutOfRangeException pops up when you try to access an array element using an index that’s either negative or larger than the maximum allowed index for that dimension of the array.
Looking at your array declaration:
Dim grade(9, 2) As Integer 'Store 10 student grades on 3 tests'
This creates a 2D array where:
- The first dimension (students) uses valid indices from
0to9(total of 10 students) - The second dimension (tests) uses valid indices from
0to2(total of 3 tests)
Common Causes & Fixes for Your Error
1. Accessing a test index greater than 2
Since you have 3 tests, their indices are 0, 1, and 2. If your code tries to use index 3 (like grade(studentCount, 3)), that’s out of bounds.
- Fix: Ensure all test-related array accesses use indices 0-2. For example, if looping through tests, use
For i As Integer = 0 To 2instead ofTo 3.
2. StudentCount exceeding 9
Your array only holds 10 students (indices 0-9). If studentCount hits 10 after adding 10 students, trying to access grade(studentCount, ...) would be grade(10, ...)—which is invalid.
- Fix: Add a check before adding a new student to cap the count at 9:
If studentCount < 10 Then ' Add the student's grades here studentCount += 1 Else MessageBox.Show("Maximum number of students (10) reached!") End If
3. Using 1-based indexing instead of 0-based
VB uses 0-based indexing for arrays by default. If you’re thinking in 1-based terms (e.g., first student = index 1, first test = index 1), you’ll eventually hit invalid indices like grade(10, 3).
- Fix: Either adjust your logic to use 0-based indices, or declare the array for 1-based access:
Dim grade(1 To 10, 1 To 3) As Integer ' Indices 1-10 for students, 1-3 for tests
Example Fix for a Typical Input Scenario
If your error line looks like this (a common mistake):
grade(studentCount, 3) = CInt(txtTest3.Text) ' THIS IS THE ERROR
Change it to use the valid test index 2:
grade(studentCount, 2) = CInt(txtTest3.Text)
内容的提问来源于stack exchange,提问作者Ethan Neuvirth

