Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Folks,

in my asp:GridViewcomponent I have the DeleteMethod setup. Also CommandField is set up:
ASP
<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" ButtonType="Image" ControlStyle-Width="24px"
    EditImageUrl="~/Images/edit-icon-png-3601.png" CancelImageUrl="~/Images/close-button-png-30225.png" UpdateImageUrl="~/Images/check-tick-icon-14150.png" DeleteImageUrl="~/Images/trash-can-24846.png" />


In OnRowDataBound() method I check for the DeleteButton and add javascript to the onclientclick event.
The javascript works, but the Ok does not lead to starting the DeleteMethod in CodeBehind.

When I do not add the javascript, the method works.

How to have a delete commandbutton work with javascript?

** Using the .NET Framework 4.7.2

What I have tried:

My code to add the javascript:

C
public static void AddDeleteMessage(GridViewRow row)
{
    int nrControls = row.Controls.Count;
    Control lastGridViewCell = row.Controls[nrControls - 1];

    var deleteButton = lastGridViewCell.Controls.OfType<ImageButton>().FirstOrDefault(btn => btn.CommandName == "Delete");
    if (deleteButton != null)
    {
        deleteButton.OnClientClick = string.Format("javascript: return confirm(\"Are you sure?\");");
    }
Posted
Updated 8-Feb-24 2:51am
v2

1 solution

WebForms link/image buttons are implemented by calling some JavaScript when you click them.

But you have added JavaScript before that which unconditionally returns true/false, meaning that this code will never be called.

If you view the source of your page, you will see something that looks like:
HTML
onclick="javascript: return confirm(...); DoPostBack(...);"
Clearly the postback method can never be called.

Change your OnClientClick to only return if the user chooses to cancel:
C#
deleteButton.OnClientClick = "if(!confirm(\"Are you sure?\")){return false;}";
 
Share this answer
 
Comments
Herman<T>.Instance 8-Feb-24 9:11am    
Works like a charm

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900