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

考えられる問題の1つは、自動番号インデックスの使用に関係しています。テーブルに新しいデータを追加しても、インデックスは生成されず、DBから自動的に取得されません。使用しているデータベースはわかりませんが、MySQLとMSSQLの例を示します。

まず、データアダプタのイベントをキャプチャする必要があります。「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

これがMSSQLの1つです。

Public Function getIdentity() As ULong
        Dim newcommand As New OleDbCommand("SELECT @@IDENTITY", connection)
        Return newcommand.ExecuteScalar()
 End Function
于 2012-06-04T20:57:47.847 に答える