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

循环DataTable所有行时触发IndexOutOfRangeException的问题求助

解决DataTable循环中访问下一行时的索引越界问题

先看你遇到的问题和原代码:

我已搜遍网络却未找到有效解决方案。在循环该DataTable并获取下一行时,总会出现dt.Rows(i+1)找不到对应行的情况。我不解的是,既然错误提示该行不存在,用if判断它是否为Nothing应可行,但仍触发异常。

你的原代码:

Dim CurrentRow As DataRow
Dim NextRow As DataRow
For i = 0 To dt.Rows.Count - 1
    'checks if taskid matches row id. if so then enter condition
    If dt.Rows(i)("TaskID") = RowID Then
        'needs to check if next row exist. if it does then get the next row . if not (hence its the final row get it)
        If dt.Rows(i + 1) Is Nothing Then
            CurrentRow = dt.Rows(i)
        Else
            NextRow = dt.Rows(i + 1)
        End If
        Exit For
    End If
Next

问题根源

你踩了一个很常见的坑:当i是DataTable的最后一行索引时(也就是i = dt.Rows.Count - 1),i+1就等于dt.Rows.Count,这时候直接访问dt.Rows(i+1)会立刻抛出索引越界异常,根本没机会执行Is Nothing的判断。因为DataRowCollection的索引范围是从0到Count-1,超出这个范围不会返回Nothing,而是直接报错。

修正后的代码

正确的做法是先判断当前索引是不是最后一个,再去访问下一行:

Dim CurrentRow As DataRow
Dim NextRow As DataRow
For i = 0 To dt.Rows.Count - 1
    If dt.Rows(i)("TaskID") = RowID Then
        ' 先判断是否是最后一行
        If i = dt.Rows.Count - 1 Then
            ' 没有下一行,赋值当前行
            CurrentRow = dt.Rows(i)
        Else
            ' 安全获取下一行
            NextRow = dt.Rows(i + 1)
        End If
        Exit For
    End If
Next

额外优化建议

如果你的需求是找到匹配行后,同时拿到当前行和下一行(如果存在),可以调整逻辑让代码更健壮:

Dim CurrentRow As DataRow
Dim NextRow As DataRow = Nothing ' 初始化下一行为空
For i = 0 To dt.Rows.Count - 1
    If dt.Rows(i)("TaskID") = RowID Then
        CurrentRow = dt.Rows(i)
        ' 只有不是最后一行时才获取下一行
        If i < dt.Rows.Count - 1 Then
            NextRow = dt.Rows(i + 1)
        End If
        Exit For
    End If
Next

这样不管有没有下一行,CurrentRow都能拿到匹配的行,NextRow如果不存在就保持Nothing,后续你可以直接判断NextRow Is Nothing来做不同的处理。

内容的提问来源于stack exchange,提问作者Goku1989

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:12:18