Gridview CommandField validation works, but not firing Delete method

3.8k Views Asked by At

I have a gridview that I'm trying to validate from code behind. In this case, to confirm a record deletion. My deletion method works fine until I add the validation which, when I implement it, it doesn't fire the deletion.

To be clear, the deletion methods work correctly until I add the RowDataBound validation.

<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" 
        />

Here are the relevant methods.

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
1

There are 1 best solutions below

0
On BEST ANSWER

You may use following code (I hope you know C# enough to translate it to VB.NET):

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);
        }
    }
}

The reason is that ImageButton control use onclick attribute to fire a postback whereas your code completely remove it's default value and postback doesn't occured at all.