Calling a functon in code behind by using an imagebutton in a gridview

后端 未结 2 967
暖寄归人
暖寄归人 2021-01-28 22:57

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

相关标签:
2条回答
  • 2021-01-28 23:17

    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.

    0 讨论(0)
  • 2021-01-28 23:28

    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 
    }
    
    0 讨论(0)
提交回复
热议问题