1

我正在使用下面提到的代码来更新和删除 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
4

1 回答 1

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
于 2012-06-04T20:57:47.847 回答