Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call JavaScript function in GridView Command Field?

I have return one Javascript function which asks the confirm message to the user. The JavaScript functions is

    function ConfirmOnDelete() {
    if (confirm("Are you sure to delete?"))
        return true;
    else
        return false;

and GridView is like below:

    <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />

Here I want to call the JavaScript function when user clicking the Delete in the GridView Command Field. How to call this?

like image 686
thevan Avatar asked Jul 26 '26 20:07

thevan


2 Answers

Assuming you want to keep using your CommandField, you could do this programmatically using your GridView's OnRowDataBound event.

Specify the event handler for the RowDataBound event in your GridView declaration:

<asp:GridView ID="gv" runat="server" OnRowDataBound="gv_RowDataBound"....

Then in your event handler (code-behind) find your button (here I'm assuming ImageButton, though this depends on your ButtonType property in your CommandField) and add JavaScript to its OnClientClick property.

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((ImageButton)e.Row.Cells[cell].Controls[ctrl]).OnClientClick = "return confirm('Are you sure you want to delete?');"; // add any JS you want here
    }
}

In the above example, cell refers to the column index of your CommandField and ctrl refers to the control index (Delete button) within the cell you're referencing.

like image 163
Brissles Avatar answered Jul 28 '26 10:07

Brissles


You better avoid ask the confirmation for deletion on the server side, capture the user final decision using javascript then go to the server side to execute your logic. CommandField will not be the best solution here.

JS:

<script type="text/javascript">
    function DeleteConfirm() {

        if (confirm("Are you sure you want to delete this customer from excluded customer list ?")) {
            return true;
        }
        return false;
    }
</script>

HTML:

            <asp:TemplateField HeaderText=" ">
                <ItemTemplate>
                    <asp:LinkButton ID="lnk_RemoveFromlist" runat="server" Text="Delete"
                        CommandName="Delete" OnCommand="Delete_Command" CommandArgument='<%# Eval("ID").ToString()' OnClientClick='return DeleteConfirm()'></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>

Code:

protected void Remove_Command(object sender, CommandEventArgs e)
{
    //Implement your Delete Logic
}
like image 38
Muhammad Hani Avatar answered Jul 28 '26 08:07

Muhammad Hani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!