Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
For Each myRow As GridViewRow In GridView3.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE * FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
Next
GridView3.DataBind()
End Sub
答案 0 :(得分:4)
我不确定为什么你认为会删除表中的所有内容,因为我相当肯定它甚至都不会执行。 DELETE
不需要指定任何列或*
。它应该是DELETE FROM hotels WHERE [etc, etc]
。
另外,您应该认真考虑阅读本文:How To: Protect From SQL Injection in ASP.NET。特别是“步骤3.使用带动态SQL的参数”,详细说明了如何更改代码以防止SQL注入。
答案 1 :(得分:0)
我相信你要找的是:
Protected Sub GridView3_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView3.RowCommand
Dim myRow As GridViewRow = DirectCast((System.Web.UI.Control)(sender)).NamingContainer, GridViewRow)
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
If e.CommandName = "Sumit" Then
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "DELETE FROM hotels WHERE hotelid =" & lab1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
End If
GridView3.DataBind()
End Sub
语法可能已关闭我对VB不太熟悉。同样最好在e.CommandArgument
中传递酒店记录的ID,这样您就不必从页面上的标签中检索它。它正在删除所有记录,因为您在网格视图中循环遍历所有行并删除每条记录。