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

替换DataGridView单元格为自定义NumericUpDownCell时类型转换异常问题

问题:DataGridView单个单元格替换为自定义NumericUpDownCell时类型转换异常

我需要实现仅将DataGridView中特定TextBox单元格替换为自定义NumericUpDownCell用于数据录入,之后再还原为普通DataGridViewTextBoxCell的场景。使用了自定义的NumericUpDownCell和NumericUpDownEditingControl类代码,通过以下代码替换单个单元格:

Private Sub ConfigureField(activeRow As DataGridViewRow)
    Try
        Dim lowerLimit As Integer = 0
        Dim upperLimit As Integer = 50
        Dim cfgValueCell = dgv(myColumn.Index, activeRow.Index)

        cfgValueCell.Dispose()
        cfgValueCell = New DataGridViewCustomNumericUpDownCell With {
                                .Minimum = lowerLimit,
                                .Maximum = upperLimit}
        dgv(myColumn.Index, activeRow.Index) = cfgValueCell

    Catch ex As Exception

    End Try
End Sub

但在NumericUpDownCell类的InitializeEditingControl方法中抛出异常:

Public Overrides Sub InitializeEditingControl(rowIndex As Integer, initialFormattedValue As Object, dataGridViewCellStyle As DataGridViewCellStyle)
    MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle)
    Dim ctl As NumericUpDownEditingControl = CType(DataGridView.EditingControl, NumericUpDownEditingControl)
    ctl.Value = CType(Me.Value, Decimal)
    ctl.Minimum = Me.Minimum
    ctl.Maximum = Me.Maximum
End Sub

异常信息:

无法将类型为'System.Windows.Forms.DataGridViewTextBoxEditingControl'的对象强制转换为类型'PrototypeUI.NumericUpDownEditingControl'。

解决方案

你遗漏了自定义单元格必须重写EditType属性——DataGridView需要通过这个属性知道单元格激活编辑时要创建哪种控件实例,否则会默认使用TextBox的编辑控件,进而导致类型转换失败。

在你的DataGridViewCustomNumericUpDownCell类中添加以下代码:

Public Overrides ReadOnly Property EditType As Type
    Get
        Return GetType(NumericUpDownEditingControl)
    End Get
End Property

另外建议同步重写ValueType属性,确保单元格值类型与编辑控件的数值类型匹配:

Public Overrides ReadOnly Property ValueType As Type
    Get
        Return GetType(Decimal)
    End Get
End Property

内容的提问来源于stack exchange,提问作者Alan O'Brien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:35:13