Covert
Covert

Reputation: 491

How do I call a JS function from ButtonField in gridview ?

I have a JavaScript function at the top of the page, I want it to call from ButtonField (type: Image) in gridview but I can't since OnClick is not available. How to do it ?

 <asp:ButtonField CommandName="cmdDelete" ImageUrl="~/assets/global/images/shopping/delete.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="20px" />

Function:

 function GetConfrim() {
            if (confirm("Are You Sure ?")) {
                return true;
            } else {
                return false;
            }
        }

And the event behind button should Only run if I press yes otherwise not.

if (e.CommandName == "cmdDelete")
            {

                MngPropertyDetails.DeletePropertyDetails(PropertyDetailsID);
                ResultLabel.ResultLabelAttributes("Record Delete Successfully!", ProjectUserControls.Enums.ResultLabel_Color.Green);
                ShowPropertyDetails();

            }

This code is inside RowCommand Event.

Upvotes: 0

Views: 2178

Answers (3)

user786
user786

Reputation: 4364

Here's how you do it,

   Button btn = (Button)e.Row.Cells[1].Controls[1];
   btn.Attributes.Add("onclick","yourFunction()");

Upvotes: 1

fubo
fubo

Reputation: 45947

that doesn't work with a ButtonField

Replace

<asp:ButtonField  CommandName="cmdDelete" ImageUrl="~/assets/global/images/shopping/delete.png" ButtonType="Image" ControlStyle-Width="25px" ControlStyle-Height="20px" />

with

<asp:TemplateField>
  <ItemTemplate>
    <asp:ImageButton ID="btnDelete" runat="server"  ImageUrl="~/assets/global/images/shopping/delete.png"  CommandName="cmdDelete" OnClientClick="return confirm('Are you Sure ?');" Width="25" Height="20"/>
  </ItemTemplate>
</asp:TemplateField>

Upvotes: 1

Ripun
Ripun

Reputation: 210

Hi you can simply display confirm box on OnclientClick as below

   <asp:ImageButton runat="server" ImageUrl="/xx/xx/icon-close.png" CausesValidation="false" CommandName="xxx"
                                    CommandArgument='xxx' OnClientClick="return confirm('Are you sure you want to delete this?');" />

Upvotes: 1

Related Questions