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

启用Option Strict On时DataGridView单元格取值的后期绑定错误解决

解决Option Strict On下DataGridView列值判断的后期绑定问题

错误原因

启用Option Strict On后,VB.NET会强制类型安全,不允许隐式类型转换和后期绑定。原代码中row.Cells("Material").Value是Object类型,直接和materialCB.Text(String类型)进行比较,属于未做显式类型转换的操作,因此触发Option Strict On disallows late binding错误。

修正方案1:显式处理DataGridView行

Dim flag As Boolean = False
For Each row As DataGridViewRow In materialsGridView.Rows
    ' 跳过DataGridView自动生成的空新行
    If Not row.IsNewRow Then
        Dim cellValue As Object = row.Cells("Material").Value
        ' 处理单元格值为DBNull的情况,避免调用ToString()时抛出异常
        Dim materialValue As String = If(cellValue Is DBNull.Value, "", cellValue.ToString())
        
        ' 按需选择字符串比较规则,OrdinalIgnoreCase表示忽略大小写
        If materialCB.Text.Equals(materialValue, StringComparison.OrdinalIgnoreCase) Then
            flag = True
            Exit For
        End If
    End If
Next

关键修改说明:

  • 显式声明row的类型为DataGridViewRow,消除隐式类型转换
  • 增加IsNewRow判断,避免遍历到无效的空行
  • 显式将单元格值转换为String,并处理DBNull的特殊情况
  • 使用Equals方法指定比较规则,符合Option Strict On的类型安全要求

修正方案2:直接遍历数据源(更高效)

如果DataGridView的数据源是DataTable,可以直接操作数据源,避免DataGridView行的额外开销:

Dim flag As Boolean = False
' 显式转换数据源为DataTable
Dim dataTable As DataTable = DirectCast(materialsGridView.DataSource, DataTable)

For Each dataRow As DataRow In dataTable.Rows
    ' 处理列值为DBNull的情况
    Dim materialValue As String = If(dataRow.IsNull("Material"), "", dataRow("Material").ToString())
    
    If materialCB.Text.Equals(materialValue, StringComparison.OrdinalIgnoreCase) Then
        flag = True
        Exit For
    End If
Next

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:15:39