2012-06-04 61 views
1

我正在使用下面提到的代碼來更新和刪除datagridview中的數據。但我無法解決這個問題。刪除正在工作,但沒有更新。如何使用vb.net更新datagridview

公用Sub CustomerUpdateBatch(BYVAL DT作爲數據表)

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

是否Anywhere錯誤?或者什麼都沒有發生?如果你通過sql-server執行它,你的存儲過程是否工作? – Yatrix

回答

0

一個可能的問題是與使用自動數字指標做。當您向表中添加新數據時,索引不會自動生成或從數據庫中提取。你不會說你有什麼數據庫,但是我會告訴你一個關於MySQL和MS SQL的例子。

首先,您需要捕獲數據適配器的事件。 「連接」和「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 
+0

他在標籤中。 Sql-Server – Yatrix

+0

確實如此,但有人可能與MySQL有相同的問題並期待,下面是一個地方的答案。 –