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

VB.NET DataGridView报BC32013编译错误,请求指导解决

VB.NET DataGridView BC32013错误修复方案

错误原因

报错Error BC32013是因为Option Strict On模式下,DataGridViewCell.FormattedValue属于Object类型,编译器禁止直接用=运算符将其与数值0比较——这种跨类型的隐式操作被严格模式拦截,同时如果单元格值为DBNull或Nothing,还会引发额外异常。

修复后的代码

将出错的判断逻辑替换为类型安全的写法,同时完善空值与数值的判断逻辑:

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, ByVal keyData As Keys) As Boolean
    ' 注意:原判断keyData的逻辑有误,若要检测Tab+Enter组合键,需改为下面的写法
    ' If (keyData And (Keys.Tab Or Keys.Enter)) = (Keys.Tab Or Keys.Enter) Then
    If keyData = Keys.Tab AndAlso CBool(Keys.Enter) Then
        Dim SelectDgv = GetSELECT()
        If Me.DataGridView1.Rows.Count > 0 Then
            ' 修复后的判断逻辑
            If Not DataGridView1.CurrentRow.Cells.Cast(Of DataGridViewCell).Any(Function(cell)
                ' 检查单元格是否为空、空字符串或仅含空格
                Dim cellText = cell.FormattedValue?.ToString().Trim()
                Return String.IsNullOrEmpty(cellText) OrElse
                       ' 尝试转换为数值,验证是否等于0
                       (Double.TryParse(cellText, Nothing) AndAlso CDbl(cellText) = 0)
            End Function) Then
                BindingSource1.AddNew()
            Else
                DataGridView1.CurrentCell = DataGridView1.CurrentRow.Cells(1)
                DataGridView1.BeginEdit(False)
            End If
        End If
        Return True
    ElseIf keyData = Keys.F1 AndAlso CBool(Keys.Enter) Then
        DataGridView1.CurrentCell = DataGridView1.CurrentRow.Cells(5)
        DataGridView1.BeginEdit(False)
    End If
    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

关键修复点

  • 先将FormattedValue转为字符串并去除空格,避免空格导致的空值误判
  • 用Double.TryParse先验证字符串是否能转换为数值,避免类型转换失败报错
  • 显式使用CDbl转换类型后再与0比较,符合Option Strict On的类型安全要求
  • 额外提示:原代码中CBool(Keys.Enter)永远返回True,如果是要检测Tab+Enter组合键,需将判断条件改为(keyData And (Keys.Tab Or Keys.Enter)) = (Keys.Tab Or Keys.Enter)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:25:10