VB.NET中DataGridView按Esc触发SetCurrentCellAddressCore函数错误求助
VB.NET DataGridView按下Esc触发SetCurrentCellAddressCore错误排查与解决
问题说明
在VB.NET项目中,当在DataGridView的m_product列输入内容后按下Esc键,会触发SetCurrentCellAddressCore函数错误。错误表现为按下Esc后程序抛出异常,诊断工具显示错误源自SetCurrentCellAddressCore方法。
代码问题分析
从提供的代码来看,核心冲突点在于:
- 你将
DataGridView1.AllowUserToAddRows设为False,禁止了DataGridView自动添加行的功能 - 但同时在
updateDataSource方法中手动调用了BindingSource1.AddNew(),新增了一行空白数据行
当在新增的空白行中输入内容后按下Esc,DataGridView尝试取消编辑并回滚该行状态,但由于AllowUserToAddRows为False,控件内部的行状态管理逻辑出现冲突,最终触发SetCurrentCellAddressCore异常。
解决指导
方案1:调整行添加逻辑(推荐)
如果需要保持手动添加行的逻辑,同时避免Esc键触发错误,可以修改代码并添加事件处理:
- 保留
AllowUserToAddRows = False,添加DataGridView的CancelRowEdit事件处理:
Private Sub DataGridView1_CancelRowEdit(sender As Object, e As QuestionEventArgs) Handles DataGridView1.CancelRowEdit ' 判断当前行是否是新增的未提交行 If BindingSource1.Current IsNot Nothing AndAlso BindingSource1.IsNew Then BindingSource1.CancelEdit() ' 如果集合为空,重新添加一行空行供输入 If list.Count = 0 Then BindingSource1.AddNew() End If End If End Sub
- 保持
updateDataSource的初始空行添加逻辑:
Private Sub updateDataSource() list = New BindingList(Of InvoicesDetailtest)() BindingSource1 = New BindingSource With {.DataSource = list} DataGridView1.DataSource = BindingSource1 DataGridView1.AutoGenerateColumns = False DataGridView1.AllowUserToAddRows = False ' 初始添加一行空行 BindingSource1.AddNew() End Sub
方案2:启用自动添加行功能
如果不需要手动控制行添加,可以直接开启DataGridView的自动添加行功能,移除手动的AddNew()调用:
Private Sub updateDataSource() list = New BindingList(Of InvoicesDetailtest)() BindingSource1 = New BindingSource With {.DataSource = list} DataGridView1.DataSource = BindingSource1 DataGridView1.AutoGenerateColumns = False ' 启用自动添加行,移除手动AddNew() DataGridView1.AllowUserToAddRows = True End Sub
这种方式下,DataGridView会自动管理新增行的状态,按下Esc时不会触发异常。
方案3:重写DataGridView捕获异常(不推荐)
如果上述方案无法适用,可以重写DataGridView的SetCurrentCellAddressCore方法捕获异常(属于规避而非根治问题):
Public Class SafeDataGridView Inherits DataGridView Protected Overrides Sub SetCurrentCellAddressCore(columnIndex As Integer, rowIndex As Integer, setAnchorCellAddress As Boolean, validateCurrentCell As Boolean, throughMouseClick As Boolean) Try MyBase.SetCurrentCellAddressCore(columnIndex, rowIndex, setAnchorCellAddress, validateCurrentCell, throughMouseClick) Catch ex As Exception ' 捕获异常并忽略,或记录日志 End Try End Sub End Class
之后将窗体中的DataGridView替换为这个自定义控件即可。
内容的提问来源于stack exchange,提问作者dlaksmi
相关产品推荐
相关产品推荐

