You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB GradeBook程序出现System.IndexOutOfRangeException错误求助

Fixing System.IndexOutOfRangeException in Your VB GradeBook Code

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 0 to 9 (total of 10 students)
  • The second dimension (tests) uses valid indices from 0 to 2 (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 2 instead of To 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:29:07