此代码用于获取已删除记录的ID,删除记录的用户以及删除记录的日期和时间,并将其插入主题表。
到目前为止,一旦删除了一条记录,代码就会抓取多条已删除的记录。
请查看我的代码以及我做错了什么。
非常感谢您的帮助。
Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles GridView1.RowDeleted
Dim connStr As String = ConfigurationManager.ConnectionStrings("Constr").ConnectionString
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = ""
' Indicate whether the delete operation succeeded.
If e.Exception Is Nothing Then
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
'Who deleted a record?
sql += "Insert into Archives ([ID],[choice],[date_stamp],[approved],[chcknum],[DeletedBy],[dateDeleted]) "
sql += " SELECT [ID],[choice],[date_stamp],[approved],[chcknum],[login],getDate() from Depends "
sql += " inner join Emp on Depends.employee_id = Emp.employee_id where login ='" & Session.Item("UserName").ToString & "' and upass = '" & Session.Item("Password").ToString & "' and [ID] = '" & strID & "' "
End If
Response.Write(sql)
Response.End()
Try
cnn = New SqlConnection(connStr)
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
sql = ""
Catch ex As SqlException
Dim errorMsg As String = "Error in Updation"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
cnn.Close()
End Try
End Sub
我认为,我的问题在于这行代码:
Dim strID As String = GridView1.FindControl(“ID”)。Cells(1).Text
我不认为这是正确的。
答案 0 :(得分:0)
我猜你正在寻找GridView.DataKeys property。使用它来告诉您的GridView数据中的哪些列应该用作唯一标识符。
您可能还想查看代码的其他一些优化:
更新
请参阅GridViewDeletedEventArgs.Keys Property以获取已删除行的ID。 “ID”列是您用来绑定GridView的查询的一部分吗?
这是一个更好(完整)的例子:
的.aspx:
<asp:GridView ID="GridView1" DataKeyNames="ID" AutoGenerateDeleteButton="true" runat="server">
</asp:GridView>
代码隐藏,带有一些虚拟数据:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim x() = {New With {.id = 1, .name = "xxx"}, New With {.id = 2, .name = "zzz"}}
GridView1.DataSource = x
GridView1.DataBind()
End If
End Sub
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim id As Integer = CInt(e.Keys(0))
' Do your stuff!
' Don't forget to rebind the GridView, it will still have the deleted row in Viewstate.
End Sub
End Class
答案 1 :(得分:0)
如果您正在运行SQL Server,则可能更容易在表上使用删除触发器。
http://msdn.microsoft.com/en-us/library/aa258254%28v=SQL.80%29.aspx
...删除和插入是逻辑(概念)表。它们在结构上类似于定义触发器的表,即,在其上尝试用户操作的表,并保存可由用户操作更改的行的旧值或新值。