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

VB.NET中For循环填充DataGridView时不显示最后一条记录且报错

问题分析与解决

错误原因

你这段代码的核心问题是没有提前为DataGridView创建对应数量的行,直接通过MetroGrid5.Rows.Item(i)访问不存在的行索引,就会触发ArgumentOutOfRangeException;最后一条记录不显示也和行数量不匹配直接相关。

另外必须注意:你直接用字符串拼接SQL语句,存在严重的SQL注入风险,绝对不能在生产环境使用这种写法。

修复方案

方案1:直接绑定数据源(最简便高效,推荐)

完全不需要手动循环赋值,DataGridView支持直接绑定DataTable,代码更简洁且不会出错:

' 使用参数化查询避免SQL注入
Dim undeclared As New SqlDataAdapter("SELECT Description, Area, RCNsqm, LVp, ELS, YrDep, RCN, Depreciation, NAV, LV FROM APRLandImprovementTabUndeclared WHERE RefNo = @RefNo", jonsqlcon)
undeclared.SelectCommand.Parameters.AddWithValue("@RefNo", MetroTextBox4.Text)

Dim dsundeclared As New DataTable
undeclared.Fill(dsundeclared)

' 直接绑定数据源,自动生成行和列
MetroGrid5.DataSource = dsundeclared

方案2:手动添加行(如果必须手动赋值)

如果一定要用循环手动填充,需要先为每一行数据新增一行到DataGridView中,再进行赋值:

' 先改成参数化查询规避注入风险
Dim undeclared As New SqlDataAdapter("SELECT Description, Area, RCNsqm, LVp, ELS, YrDep, RCN, Depreciation, NAV, LV FROM APRLandImprovementTabUndeclared WHERE RefNo = @RefNo", jonsqlcon)
undeclared.SelectCommand.Parameters.AddWithValue("@RefNo", MetroTextBox4.Text)

Dim dsundeclared As New DataTable
undeclared.Fill(dsundeclared)

If dsundeclared.Rows.Count > 0 Then
    ' 清空现有行(可选,根据业务需求决定)
    MetroGrid5.Rows.Clear()
    
    For i As Integer = 0 To dsundeclared.Rows.Count - 1
        ' 先新增一行,获取行索引
        Dim rowIndex As Integer = MetroGrid5.Rows.Add()
        Dim gridRow = MetroGrid5.Rows(rowIndex)
        
        gridRow.Cells(0).Value = dsundeclared.Rows(i)("Description").ToString
        gridRow.Cells(1).Value = dsundeclared.Rows(i)("Area").ToString
        gridRow.Cells(2).Value = dsundeclared.Rows(i)("RCNsqm").ToString
        gridRow.Cells(3).Value = dsundeclared.Rows(i)("LVp").ToString
        gridRow.Cells(4).Value = dsundeclared.Rows(i)("ELS").ToString
        gridRow.Cells(5).Value = dsundeclared.Rows(i)("YrDep").ToString
    Next
End If

关键注意点

  • 必须使用参数化查询替代字符串拼接,彻底避免SQL注入攻击
  • 手动填充时一定要先调用Rows.Add()新增行,再访问对应索引的行,不能直接访问不存在的索引

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:17:31