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

VB.NET中BindingSource绑定DataGridView后删除行更新数据库报错求助

解决BindingSource绑定DataGridView后更新数据库报错的方案

问题原因

  1. 删除行时直接操作DataGridView的Rows集合,未同步更新BindingSource绑定的List数据源,导致后续遍历行时部分DataBoundItem失效,转换抛出异常。
  2. 遍历DataGridView.Rows时会包含默认的新增空行,该行的DataBoundItem为Nothing,DirectCast转换时触发错误。

具体修复方案

1. 修正删除逻辑:通过BindingSource操作数据源

直接对BindingSource进行删除操作,确保数据源与控件状态同步,同时跳过新增空行:

Private Sub BTNDELETE_Click(sender As Object, e As EventArgs) Handles BTNDELETE.Click
    ' 倒序删除,避免索引偏移导致的删除遗漏
    For i = DataGridView1.SelectedRows.Count - 1 To 0 Step -1
        Dim selectedRow = DataGridView1.SelectedRows(i)
        If selectedRow.IsNewRow Then Continue For ' 跳过未保存的新增空行
        _source.Remove(selectedRow.DataBoundItem)
    Next
    DataGridView1.Refresh()
End Sub

2. 优化更新逻辑:遍历BindingSource数据源而非DataGridView行

直接操作绑定的数据源集合,避免遍历到无效的空行:

Private Sub BTNUPDATE_Click(sender As Object, e As EventArgs) Handles BTNUPDATE.Click
    Try
        ' 从BindingSource获取绑定的数据源集合
        Dim personList = DirectCast(_source.DataSource, List(Of persondetail))
        If personList.Count = 0 Then
            Throw New Exception("无数据可更新")
        End If
        ' 遍历数据源集合,直接更新每一条数据
        For Each detail In personList
            pservice.UpdatePersondetail(detail)
        Next
        MessageBox.Show("更新成功")
    Catch ex As Exception
        MessageBox.Show(ex.Message, "应用提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    End Try
End Sub

3. 可选优化:用BindingList替代List增强绑定稳定性

BindingList(Of T)实现了IBindingList接口,支持数据源更改通知,让BindingSource能自动同步控件与数据源的状态,减少绑定异常:

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim personList = pservice.GetPersondetail()
    ' 将List转换为BindingList后绑定到BindingSource
    _source.DataSource = New BindingList(Of persondetail)(personList)
    DataGridView1.DataSource = _source
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:25:24