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

DataGridView文本框控件类型转换错误(BC30311)求助

问题原因及解决办法

错误根源

出现BC30311错误的核心原因是:你尝试将第4列的编辑控件直接强制转换为TextBox,但该列的编辑控件并非TextBox类型,导致类型转换失败。

常见触发场景:

  • 第4列不是DataGridViewTextBoxColumn(比如误设为DataGridViewComboBoxColumn、DataGridViewCheckBoxColumn等其他列类型),其对应的编辑控件自然不是TextBox。
  • 即使是DataGridViewTextBoxColumn,它的编辑控件实际是DataGridViewTextBoxEditingControl(继承自TextBox),若代码上下文类型检查严格,也可能触发转换错误。

修复方案

方案1:先校验控件类型再转换

用TryCast替代CType,转换失败时返回Nothing而非抛出错误,同时先判断列索引再处理,逻辑更严谨:

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    ' 处理第4列的文本框事件
    If DataGridView1.CurrentCell.ColumnIndex = 4 Then
        Dim quantityTextBox As TextBox = TryCast(e.Control, TextBox)
        If quantityTextBox IsNot Nothing Then
            RemoveHandler quantityTextBox.KeyUp, AddressOf quantity_KeyUp
            AddHandler quantityTextBox.KeyUp, AddressOf quantity_KeyUp
        End If
    End If

    ' 处理第2列的ComboBox事件
    If DataGridView1.CurrentCell.ColumnIndex = 2 Then
        Dim cmb As ComboBox = CType(e.Control, ComboBox)
        RemoveHandler cmb.SelectedIndexChanged, AddressOf Cmb_SelectedIndexChanged
        AddHandler cmb.SelectedIndexChanged, AddressOf Cmb_SelectedIndexChanged
    End If
End Sub

方案2:确认第4列的列类型

检查DataGridView第4列(索引从0开始)的类型:

  1. 在设计视图选中DataGridView,打开列编辑器。
  2. 找到索引为4的列,确认其类型为DataGridViewTextBoxColumn,若不是则修改为该类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:25:38