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

DataGridView数据源需离开编辑行才更新问题咨询

问题描述

将DataGridView的DataSource绑定到DataTable后,通过CellValueChanged事件获取变更时,GetChanges()在离开编辑行前始终返回Nothing,按Tab键也无效,只有按下箭头键后才返回有效结果,请问原因是什么?是否需要处理其他事件?

用户代码示例:

Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    Dim dtChanges As DataTable = CType(DataGridView1.DataSource, DataTable).GetChanges
End Sub
原因及解决方案

原因

DataGridView在单元格处于编辑状态时,不会立即将修改的值提交到绑定的DataTable中——只有当单元格失去焦点且完全结束编辑状态时,才会把值同步到DataTable:

  • 按Tab键仅移动到同一行的下一个单元格,当前行仍处于编辑状态,DataTable不会接收变更
  • 按下箭头键切换到其他行时,当前行的编辑状态被彻底结束,变更才会同步到DataTable,此时GetChanges()才能捕获到修改

解决方案

有两种可行的处理方式:

  • 主动结束单元格编辑
    在CellValueChanged事件中先强制结束编辑,确保值同步到DataTable后再获取变更:
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
    ' 强制结束当前单元格编辑,同步值到DataTable
    DataGridView1.EndEdit()
    Dim dtChanges As DataTable = CType(DataGridView1.DataSource, DataTable).GetChanges
End Sub
  • 改用CellEndEdit事件
    如果不需要在单元格值变化的瞬间处理,而是等编辑完全结束后再操作,直接绑定CellEndEdit事件更贴合场景:
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
    Dim dtChanges As DataTable = CType(DataGridView1.DataSource, DataTable).GetChanges
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 20:54:52