VB.NET中如何重置DataGridView内BindingSource/BindingList的序号
问题解决:VB.NET删除DataGridView行后重置序号
你的问题出在直接修改DataGridView的单元格值,而没有更新绑定数据源(BindingList(Of Product))中的No属性。因为DataGridView是绑定到BindingSource的,UI显示的内容完全来自数据源,直接修改UI单元格不会同步到数据源,后续刷新后会恢复原数值。
修复方案
1. 确保Product类实现INotifyPropertyChanged(推荐)
实现该接口后,修改数据源对象的属性时,DataGridView会自动同步更新UI:
Public Class Product Implements INotifyPropertyChanged Private _no As Integer Private _codeproduct As String Private _qty As Integer Private _qty_Stock As Integer Public Property No As Integer Get Return _no End Get Set(value As Integer) If _no <> value Then _no = value OnPropertyChanged(NameOf(No)) End If End Set End Property Public Property Codeproduct As String Get Return _codeproduct End Get Set(value As String) If _codeproduct <> value Then _codeproduct = value OnPropertyChanged(NameOf(Codeproduct)) End If End Set End Property Public Property Qty As Integer Get Return _qty End Get Set(value As Integer) If _qty <> value Then _qty = value OnPropertyChanged(NameOf(Qty)) End If End Set End Property Public Property Qty_Stock As Integer Get Return _qty_Stock End Get Set(value As Integer) If _qty_Stock <> value Then _qty_Stock = value OnPropertyChanged(NameOf(Qty_Stock)) End If End Set End Property Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged Protected Sub OnPropertyChanged(propertyName As String) RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName)) End Sub End Class
2. 修改删除事件中的序号重置逻辑
删除记录后,直接遍历数据源更新每个Product的No属性,而非修改UI单元格:
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick If DataGridView1.Columns(e.ColumnIndex) Is DataGridView1.Columns("Coldel") Then If DataGridView1.SelectedRows.Count = 0 Then Return End If If MessageBox.Show("Delete selected record?", "CONFIRM!", MessageBoxButtons.YesNoCancel) = DialogResult.Yes Then Dim product = GetProduct() Dim bs = TryCast(bindingSource.DataSource, BindingList(Of Product)) ' 执行数据库删除操作 bs.Remove(product) ' 重置序号:遍历数据源更新每个Product的No属性 For i As Integer = 0 To bs.Count - 1 bs(i).No = i + 1 Next ' 若未实现INotifyPropertyChanged,取消下面注释强制刷新UI ' bindingSource.ResetBindings(False) ' 执行数据库保存更新后的序号操作 End If End If End Sub
关键说明
- 数据绑定模式下,所有数据操作都应针对数据源进行,而非直接修改UI,这是数据绑定的核心原则。
- 若不实现
INotifyPropertyChanged,需调用bindingSource.ResetBindings(False)强制刷新UI,确保修改后的序号显示生效。
内容的提问来源于stack exchange,提问作者user22579796
相关产品推荐
相关产品推荐

