Calling a functon in code behind by using an image

2020-05-05 17:51发布

问题:

I have an ImageButton within a GridView in .aspx on clicking this ImageButton i have to call a function. This is how i tried and the function was not being called. Code inside.aspx page:

<GridView ......>
    <asp:HyperLink ID="HyperLink2" runat="server" 
        NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"VehID","mngVeh.aspx?delid={0}") %>'>   
        <asp:ImageButton runat="server" ID="DeleteUrlImageButton" 
            width='24' height='24'
            ImageUrl="~/images/delete.jpeg" 
            OnClick="DeleteUrlImageButton_Click"
            OnClientClick="return confirm('Are you sure you want to delete?');" />
        <!--<img src="images/delete.jpeg" alt='edit' border="0" width='24' height='24'/> -->
   </asp:HyperLink>
</GridView>

code in .aspx.cs page:

public void DeleteUrlImageButton_Click(object sender, EventArgs e)
{
    //code to perform the necessary action.
}

回答1:

Because you are wrapping your ImageButton inside of a Hyperlink, the browser is probably going to the hyperlink's URL instead of posting back to hit the OnClick function. You should have the DeleteUrlImageButton_Click function call Server.Transfer or Response.Redirect to the appropriate URL and get rid of the Hyperlink.



回答2:

Sure it won't be fired because it is nested in a Hyperlink. So the imagebutton serves as the text for the hperlink and hyperlink does not cause postback. ImageButton can cause the desired action only if it stands out of the Hyperlink. Try this:

<asp:GridView ....
<asp:TemplateField ShowHeader="False">
    <ItemTemplate>
     <asp:ImageButton runat="server" ID="DeleteUrlImageButton" 
        width='24' height='24'
        ImageUrl="~/images/delete.jpeg" 
        OnClick="DeleteUrlImageButton_Click"
        OnClientClick="return confirm('Are you sure you want to delete?');" 
  PostBackUrl='<%# DataBinder.Eval(Container.DataItem,"VehID","mngVeh.aspx?delid={0}")
 %>'/>
  </ItemTemplate>
  </asp:TemplateField>
</asp:GridView>

ImageButton can do the job no need for Hyperlink just use the postbackurl and it will redirect you to the page. You can omit the HyperLink. Button controls (like LinkButton,ImageButton and Button) are designed to cause postback by default.

Edit: Make sure event name and arguments are correct. This is the event I used to test it. y the way don't forget to place the ImageButton in a TemplateField, refer the code above

protected void DeleteUrlImageButton_Click(object sender, ImageClickEventArgs e)
{
    TextBox5.Text = "Fired ";

 //Response.Redirect( ((ImageButton)sender).PostBackUrl);//uncomment this if the button does not automatically redirects. This line should be the last one 
}


标签: c# asp.net