views:

33

answers:

1

How to call javascript function when using validation controls on GridView.

I am trying to call confirmDelete function on delete button of GridViews delete button. I dont have a code as of now. But when I was trying it was throwing an exception at javascript

A: 

Here is a sample code how I use javascript confirm on GridView:

<asp:GridView ID="gv" runat="server" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:ImageButton ID="btnDelete" runat="server" OnCommand="btnDelete_Command" 
                    CommandArgument='<%# Eval("Id") %>' ImageUrl="~/img/delete.png" 
                    OnClientClick="return btnDelete_Click()"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<script type="text/javascript">
    function btnDelete_Click() {
        return window.confirm('You sure?');
    }
</script>

Code behind:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gv.DataSource = list;
        gv.DataBind();
    }
}

protected void btnDelete_Command(object sender, CommandEventArgs e)
{
    // Delete Operation.
}

I hope it will be helpful.

Musa Hafalır
@Musa: This kind of Code I have written. Every thing in the button part is same, Only thing that I added is validation and after adding validation controls of asp.net. My confirm button stopped working. A javascript exception is occuring now again and again.
Shantanu Gupta
Can you write the javascript exception message?
Musa Hafalır
@Musa: I am getting this error **Microsoft JScript runtime error: Object expected**
Shantanu Gupta
`<input type="image" name="ctl00$ctl00$cphBody$midbox$gvProcedure$ctl08$btnDelete" id="ctl00_ctl00_cphBody_midbox_gvProcedure_ctl08_btnDelete" src="../images/delete.jpg" alt="Delete" onclick="return ConfirmDelete();" style="border-width:0px;" />` This is my line on which javascript error is occuring. ConfirmDelete function resides in external js file
Shantanu Gupta
May be your page cannot get through the external js file. May be there is a problem with <script src="Scripts/site.js" type="text/javascript"></script> tag inside the <head> tags. You can try it with the scripts inside the page or be sure to add external js file to the page succesfully. Good luck.
Musa Hafalır
Or ofcourse you can just do: <asp:ImageButton ID="btnDelete" runat="server" OnCommand="btnDelete_Command" CommandArgument='<%# Eval("Id") %>' ImageUrl="~/img/delete.png" OnClientClick="return window.confirm('You Sure?');"/>
Musa Hafalır