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

DataGridView设置CurrentCell触发重入调用错误的解决方法求助

解决DataGridView设置CurrentCell时的重入调用错误

问题原因

在CellEnter事件处理过程中直接修改CurrentCell,会触发新的CellEnter事件,形成重入调用,导致控件内部的SetCellAddressCore函数被重复调用,从而抛出错误。

解决方案

使用Control.BeginInvoke延迟执行设置CurrentCell的操作,让当前的CellEnter事件处理完成后,再执行焦点切换逻辑,避免重入。

具体代码实现

Private Sub DataGridView1_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEnter
    ' 仅当进入存储助手ID的列(索引13)时执行逻辑
    If e.ColumnIndex = 13 Then
        Dim helperIds As New List(Of Integer)()
        Dim cellValue = DataGridView1.Rows(e.RowIndex).Cells(13).Value
        ' 处理Null值并转换为整数
        If cellValue IsNot DBNull.Value AndAlso Integer.TryParse(cellValue.ToString(), Nothing) Then
            helperIds.Add(CInt(cellValue))
        End If

        If helperIds.Count > 0 Then
            ' 替换为实际查询助手姓名的逻辑
            Dim names As New List(Of String)()
            For Each id In helperIds
                names.Add($"助手{id}")
            Next

            ' 显示助手姓名
            MessageBox.Show(String.Join(vbCrLf, names))

            ' 延迟设置当前单元格,避免重入调用
            Me.DataGridView1.BeginInvoke(Sub()
                                             Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(e.RowIndex).Cells(1)
                                         End Sub)
        End If
    End If
End Sub

补充说明

  • BeginInvoke会将焦点切换逻辑加入UI线程的消息队列,等待当前CellEnter事件处理流程结束后再执行,彻底规避重入问题。
  • 增加列索引判断,只在进入助手ID列时执行逻辑,减少不必要的性能消耗。
  • 提前处理单元格Null值,避免类型转换时出现异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 10:53:13