[英]How to update a datagridview using vb.net
我正在使用下面提到的代码来更新和删除datagridview中的数据。 但是我无法解决这个问题。 删除有效,但无法更新。
公共子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
一个可能的问题与使用自动编号索引有关。 当您向表中添加新数据时,索引不会自动生成或从数据库中获取。 您没有说您拥有什么数据库,但是我将向您展示MySQL和MS SQL的示例。
首先,您需要捕获数据适配器的事件。 “连接”和“数据适配器”定义将需要在函数之外:
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 Server。 这是针对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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.