0

I have a dynamic ImageButton and I want it to trigger a method when it's clicked. I have the following code, which unfortunatelly it's not working.

ImageButton imb = new ImageButton();
imb.Attributes.Add("runat", "server");
        imb.Click += new ImageClickEventHandler(ImageButton1_Click);
        imb.ID = "ID";
        imb.ImageUrl = "link to image";
Panel1.Controls.Add(imb);

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    //it should go here
}
  • You spelled `runat` wrong. Also, OnClientClick is for javascript, remove that. Is there some reason you can't just put the control on the page? – wazz May 27 '18 at 14:58
  • [Version in VB](https://stackoverflow.com/questions/19098325/how-to-hook-up-clicki-event-for-imagebutton-in-code-behind-asp-net). – wazz May 27 '18 at 15:05
  • Fixed 'runat' and removed OnClientClick. The control is added to an ASP Panel, but still doesn't work. – Darena M Ivanova May 27 '18 at 15:14
  • Update your question with the current code. – wazz May 27 '18 at 15:26
  • Question updated with the current code. – Darena M Ivanova May 27 '18 at 15:41
  • imb.Attributes.Add("runat", "server"); not needed at all because it is only needed in aspx /ascx markup only. while adfing from code behind it's not needed. also dynamically added control need to be added always on PostBack. – par May 27 '18 at 15:50

2 Answers2

0

you must add your ImageButton to a suitable continer.

e.g:

 form1.Controls.Add(Imb);
 /// form1 must have runat=server

you can find useful tips at here.

RezaNoei
  • 1,266
  • 1
  • 8
  • 24
0

Adding dynamic controls to the page is a tricky matter. Unfortunately, you cannot just declare an object of WebControl derived type and expect it to work.

In ASP.NET WebForms, there is a concept called Page Lifecycle. It is a broad matter, but my point is that there is a particular order you must obey to plug-in the dynamic control into the page. A practical example follows.

Start with dynamic control declaration at the class level.

protected ImageButton imb = null;

Then you initialize it durring the page initialization. One possibility is to handle the PreInit event.

protected void Page_PreInit(object sender, EventArgs e)
{
    imb = new ImageButton()
    {
        ID = "ID",
        ImageUrl = "link to image"
    };

    imb.Click += Imb_Click;

    Panel1.Controls.Add(imb);

}

private void Imb_Click(object sender, ImageClickEventArgs e)
{
    // Do your stuff
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Set initial properties as appropriate. E.g.
        imb.AlternateText = "...";
    }
}

You're good to go.

Bozhidar Stoyneff
  • 3,576
  • 1
  • 18
  • 28