首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Gridview验证有效,但不触发CommandField方法

Gridview验证有效,但不触发CommandField方法
EN

Stack Overflow用户
提问于 2011-11-21 23:35:12
回答 1查看 3.8K关注 0票数 1

我有一个网格视图,我正在试着从代码背后验证它。在这种情况下,确认删除记录。我的删除方法工作得很好,直到我添加了验证,当我实现它时,它不会触发删除。

为了清楚起见,在我添加RowDataBound验证之前,删除方法可以正常工作。

代码语言:javascript
复制
<asp:CommandField 
        ButtonType="Image"
        ShowEditButton="true" 
        ShowDeleteButton="true" 
        ShowCancelButton="true"
        EditImageUrl="~/Images/edit-icon.gif" 
        UpdateImageUrl="~/Images/save-icon.png"
        CancelImageUrl="~/Images/cancel-icon.png" 
        DeleteImageUrl="~/Images/delete-icon.png" 
        />

以下是相关的方法。

代码语言:javascript
复制
Protected Sub usersGrid_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
For Each control As Control In e.Row.Cells(0).Controls
        Dim DeleteButton As ImageButton = TryCast(control, ImageButton)
        If DeleteButton IsNot Nothing AndAlso DeleteButton.CommandName = "Delete" Then
            DeleteButton.OnClientClick = "return(confirm('Are you sure you want to delete this user?\nThis cannot be undone!'))"
        End If
    Next
End Sub

Protected Sub usersGrid_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
    Dim userID As Integer = DirectCast(usersGrid.DataKeys(e.RowIndex).Value, Integer)

    usersGrid_Delete(userID)
    BindData()
End Sub

Protected Sub usersGrid_Delete(ByVal userID As Integer)
    Dim con As New SqlConnection(connectionString)
    Dim cmd As New SqlCommand("MAINT_DIST_DELETE_USER", con)
    cmd.CommandType = CommandType.StoredProcedure
    cmd.Parameters.AddWithValue("@userID", userID)

    Try
        con.Open()
        cmd.ExecuteNonQuery()
    Catch Ex As Exception
        Throw Ex
    Finally
        con.Close()
    End Try
End Sub
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-11-22 00:14:36

您可以使用以下代码(我希望您了解足够多的C#以将其转换为VB.NET):

代码语言:javascript
复制
void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var deleteButton = e.Row.Cells[0].Controls.OfType<ImageButton>().FirstOrDefault(btn => btn.CommandName == "Delete");
        if (deleteButton != null)
        {
            deleteButton.OnClientClick =
                string.Format("javascript:if(confirm('Are you sure you want to delete this user? This cannot be undone!')){{ __doPostBack('{0}', 'Delete${1}');}} return false;", GridView1.UniqueID, e.Row.RowIndex);
        }
    }
}

原因是ImageButton控件使用onclick属性来触发回发,而您的代码完全删除了它的默认值,因此根本不会发生回发。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8214255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档