我只是注意到,如果用户修改了DataGridView
中的内容并且还选择了最后一个(新)行而没有在其中输入任何数据,那么当HasChanged
事件触发此最后一个新行时包含在要添加到数据库中的那些。然后我得到一个错误,因为我无法将该记录放在数据库中,因为空值。我想在这种特殊情况下排除这一行,因为它不应被视为要添加的行。以下是我目前的代码:
For Each row As DataGridViewRow In Grid.Rows
If Not row.IsNewRow Then
Dim cellValue As String = String.Empty
For i = 1 To row.Cells.Count - 1
cellValue = row.Cells(i).Value.ToString
If String.IsNullOrEmpty(cellValue) Then
MsgBox("All fields has to be filled out")
Exit Sub
End If
Next
End If
Next
marke.MakeChangesDS()
Public Sub MakeChangesDataSet() Implements IDAL.MakeChangesDataSet
If Not GetGeschaftDataSet.HasChanges Then
MessageBox.Show("No changes to be done", "Informacja", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Else
Dim i As Integer
Try
Using MyConnection = New SqlConnection(strcon)
Using cmd As New SqlCommand("SELECT * FROM T_Marke", MyConnection)
MyConnection.Open()
' Create a data adapter in the method and throw it away afterwards
Using GetProjectsDataAdapter = New SqlDataAdapter(cmd)
Dim cmdbuilder As New SqlCommandBuilder(GetProjectsDataAdapter)
i = GetProjectsDataAdapter.Update(GetGeschaftDataSet, "trial1")
End Using
End Using
End Using
MessageBox.Show("Updated" & i & " marks", "Informacja", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
我想我应该在MakeChangesDataSet函数中检查并排除它。
答案 0 :(得分:0)
SqlDataAdapter类有一个名为RowUpdating的事件处理程序,它允许您检查行是否有效,如果您选择这样做,则取消该行的更新。
.....
Using GetProjectsDataAdapter = New SqlDataAdapter(cmd)
Dim cmdbuilder As New SqlCommandBuilder(GetProjectsDataAdapter)
AddHandler GetProjectsDataAdapter.RowUpdating, AddressOf onUpdate
i = GetProjectsDataAdapter.Update(GetGeschaftDataSet, "trial1")
RemoveHandler GetProjectsDataAdapter.RowUpdating, AddressOf onUpdate
End Using
在实际更新/插入/删除发生之前,需要更新的每一行都会调用此事件。事件处理程序代码接收决定如何处理数据所需的所有信息。您将获得StatementType
,告诉您这是INSERT,UPDATE还是DELETE操作。然后,您可以决定在数据库引擎引发任何异常之前如何处理SqlRowUpdatingEventArgs.Status
行设置。
Sub OnUpdate(sender as Object, args As SqlRowUpdatingEventArgs)
If args.StatementType = StatementType.Insert Then
if Not IsYourRowValid(args.Row) Then
args.Status = UpdateStatus.SkipThisRow
End If
End If
End Sub