GridView ImageButton 确认和删除记录
Posted
技术标签:
【中文标题】GridView ImageButton 确认和删除记录【英文标题】:GridView ImageButton confirm and delete record 【发布时间】:2011-11-15 19:12:24 【问题描述】:我在这里遇到了一个大问题。我已经设法将 javascript 添加到我的服务器端,但它没有删除的问题。它没有产生任何错误,所以我不知道从哪里开始:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "cmdDelete" Then
Dim ID As Integer = Convert.ToInt32(e.CommandArgument)
End If
End Sub
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim l As ImageButton = DirectCast(e.Row.FindControl("ImageDelete"), ImageButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this record " & DataBinder.Eval(e.Row.DataItem, "ID") & "')")
End If
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim ID As Integer = CInt(GridView1.DataKeys(e.RowIndex).Value)
'dim ID as Integer
con.Open()
'gridview1.rows(e.rowindex).cells(0)
Dim cmd As New SqlCommand("delete from [tblUser] where [ID]=@ID", con)
cmd.Parameters.AddWithValue("@ID", ID)
cmd.ExecuteNonQuery()
con.Close()
End Sub
客户端
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImageDelete" ImageUrl="" runat="server" CommandName="cmdDelete" CommandArgument='<%# Eval("ID") %>'
/>
</ItemTemplate>
</asp:TemplateField>
</Columns
【问题讨论】:
您看到 javascript 确认消息了吗?当你按下是/确定时,它会引发 RowCommand 事件吗? 【参考方案1】:当按下ImageDelete
按钮时,会发生RowCommand
事件。但是,在RowCommand
的事件处理程序中,您不会删除任何内容。另一方面,RowDeleting
事件根本不会发生,因为此事件的正确命令是 Delete
,而不是 cmdDelete
。
我看到了两种可能的解决方法。首先 - 将删除操作的代码移动到 RowCommand
事件处理程序:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "cmdDelete" Then
Dim ID As Integer = Convert.ToInt32(e.CommandArgument)
con.Open()
Dim cmd As New SqlCommand("delete from [tblUser] where [ID]=@ID", con)
cmd.Parameters.AddWithValue("@ID", ID)
cmd.ExecuteNonQuery()
con.Close()
End If
End Sub
第二 - 更改命令名称并使用您已经实现的 RowDeleting
处理程序:
<asp:ImageButton ID="ImageDelete" ImageUrl="" runat="server" CommandName="Delete" CommandArgument='<%# Eval("ID") %>' />
【讨论】:
先生,我所做的是在客户端添加CommandField
中的删除按钮只是向服务器发送Delete
命令,导致RowDeleting
事件发生。这就是它起作用的原因。【参考方案2】:
您尚未在标记中显示是否将 ID 作为数据键添加到 GridView。
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" ...>
而且我认为您在删除逻辑中检索 ID 的方式可能存在问题:
Dim ID As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex)("ID"))
【讨论】:
以上是关于GridView ImageButton 确认和删除记录的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Yii2 Gridview 中自定义默认数据确认对话框
android.widget.RelativeLayout 无法转换为 android.widget.ImageButton
如何在 ASP.Net Gridview 中添加“确认删除”选项?