我正在尝试使用 VB.NET 重置 DataGridView 中的 BindingSource/BindingList 序列号。
或者我的代码实现出了问题
请指导我。
下面我还附上截图和代码
谢谢
Public Class Form1
Private bindingSource As BindingSource = Nothing
Private Function GetProduct() As Product
Return If(DataGridView1.SelectedCells.Count = 0, Nothing, TryCast(DataGridView1.SelectedCells(0).OwningRow.DataBoundItem, Product))
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim list = New List(Of Product)() From {
New Product With {
.No = 1,
.Codeproduct = "1000",
.Qty = 20,
.Qty_Stock = 50
},
New Product With {
.No = 2,
.Codeproduct = "2000",
.Qty = 30,
.Qty_Stock = 40
},
New Product With {
.No = 3,
.Codeproduct = "3000",
.Qty = 30,
.Qty_Stock = 40
}
}
bindingSource = New BindingSource With {.DataSource = New BindingList(Of Product)(CType(list, IList(Of Product)))}
DataGridView1.DataSource = bindingSource
DataGridView1.Columns("No").ReadOnly = True
DataGridView1.Columns("Codeproduct").ReadOnly = True
DataGridView1.Columns("Qty").ReadOnly = True
DataGridView1.Columns("Qty_Stock").ReadOnly = True
DataGridView1.Columns("Coldel").ReadOnly = True
End Sub
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))
'do method service sql to database
bs.Remove(product)
DataGridView1.Refresh()
'update code
Dim counter As Integer = 0
For Each row As DataGridViewRow In DataGridView1.Rows
counter += 1
'row.Cells("No").Value = counter
row.Cells("No").Value = If(row.Index = DataGridView1.NewRowIndex, Nothing, counter)
Next row
'do method service sql save to database
End If
End If
End Sub
End Class
删除前
No
2
删除后
No
2
所以在结果中希望数字 3 成为数字 2
新的网格行显示数据绑定对象的默认值。对于引用类型,如果值什么都没有,新行将不显示任何内容,或者如果您想提供默认值而不是 Nothing
/
DbNull
,则显示列 DefaultCellStyle.NullValue属性的值。
对于像
No
列这样的值类型,数据绑定项的类型为 Integer
,因此,新行显示该类型的默认值 0
。不,您不能在此处使用 NullValue
属性来更改它。
要隐藏
0
列中的默认值 No
,您有两种选择。要么将属性转换为模型中可为空的整数:
Public Class Product
Public Property No As Integer?
' ...
End Class
或设置 DefaultCellStyle.Format 属性来隐藏零值。例如,
#
格式说明符。有关更多信息,请参阅自定义数字格式字符串。
DataGridView1.Columns("No").DefaultCellStyle.Format = "#"