我使用下面提到的代码来更新和删除datagridview中的数据。但我无法解决这个问题。删除工作正常但未更新。
Public Sub CustomerUpdateBatch(ByVal dt As DataTable)
Dim connection As SqlConnection = New SqlConnection(Invoice.GetConnect())
connection.Open()
Try
Dim command As SqlCommand = New SqlCommand("Update_Customer", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@C_ID", SqlDbType.Int, 16, "C_ID")
command.Parameters.Add("@C_Name", SqlDbType.VarChar, 50, "C_Name")
command.Parameters.Add("@C_Address", SqlDbType.VarChar, 50, "C_Address")
command.Parameters.Add("@C_Tel", SqlDbType.VarChar, 50, "C_Tel")
command.Parameters.Add("@C_Fax", SqlDbType.VarChar, 50, "C_Fax")
command.Parameters.Add("@C_Mobile", SqlDbType.VarChar, 50, "C_Mobile")
command.Parameters.Add("@C_Email", SqlDbType.VarChar, 50, "C_Email")
command.Parameters.Add("@C_Tin", SqlDbType.VarChar, 50, "C_Tin")
command.Parameters.Add("@C_Remarks", SqlDbType.VarChar, 50, "C_Remarks")
command.CommandType = CommandType.StoredProcedure
Dim delcommand As SqlCommand = New SqlCommand("Delete_Customer", connection)
delcommand.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@C_ID", SqlDbType.Int, 16, "C_ID")
Dim adapter As SqlDataAdapter = New SqlDataAdapter()
adapter.UpdateCommand = command
adapter.DeleteCommand = delcommand
adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None
adapter.Update(dt)
Catch ex As Exception
Console.WriteLine(ex.Message)
Throw
Finally
connection.Close()
End Try
End Sub
答案 0 :(得分:0)
一个可能的问题与使用自动编号索引有关。向表中添加新数据时,不会自动生成或从数据库中获取索引。您没有说出您拥有的数据库,但我将向您展示MySQL和MS SQL的示例。
首先,您需要捕获数据适配器的事件。 “Connection”和“Dataadapter”定义需要在您的函数之外:
Dim WITHEVENTS adapter As SqlDataAdapter = New SqlDataAdapter()
然后你需要有一个函数来捕获这些事件:
Private Sub myAdapter_RowUpdated(ByVal sender As Object, ByVal e As System.Data.OleDb.OleDbRowUpdatedEventArgs) Handles adapter.RowUpdated
If (e.StatementType = StatementType.Insert And e.Status = UpdateStatus.Continue) Then
Dim id As ULong = getIdentity()
If (id > 0) Then
e.Row(0) = id
End If
End If
End Sub
getIdentiy()函数需要特定于您的SQL服务器。这个是针对MySQL的:
Public Function getIdentity() As ULong
Dim newcommand As New MySqlCommand("SELECT LAST_INSERT_ID();", connection)
Return newcommand.ExecuteScalar()
End Function
这是MS SQL的一个:
Public Function getIdentity() As ULong
Dim newcommand As New OleDbCommand("SELECT @@IDENTITY", connection)
Return newcommand.ExecuteScalar()
End Function