This code is intended to grab the ID of the deleted record, the user who deleted the record, and the date and time the record was deleted and insert it into a hostical table.
So far, once a record is deleted, the code grabs more than one deleted record.
Please see my code and what I am doing wrong.
Thanks alot in advance for your help.
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
My problem, I think, lies in this line of code:
Dim strID As String = GridView1.FindControl(“ID”).Cells(1).Text
I don’t think it is correct.
I’m guessing you’re looking for the GridView.DataKeys property. Use it to tell your GridView which column(s) in the data is should use as an unique identifer.
You probably also want to look into a few other optimzations for your code:
Update:
See the GridViewDeletedEventArgs.Keys Property to get the ID of the deleted row. Is the “ID” column part of the query you’re using to bind the GridView?
Here’s a better (complete) example:
.aspx:
Code-behind, with some dummy data: