1

I am just trying to add onClick event to dynamically created ImageButton, and it should be easy, but for some reason, my click event is not firing, no matter what I do.

I created a couple of image buttons and add them to the table.

Here is my code for that bit:

TableCell cell= new TableCell();
ImageButton pic= new ImageButton();
pic.Click += new ImageClickEventHandler(pic_Click);
pic.ImageUrl = "~/Pictures/" + list[j];
pic.Width = 180;
pic.Height = 150;
pic.BorderStyle = BorderStyle.Inset;
pic.BorderColor = Color.DarkRed;
cell.Controls.Add(pic);
row.Cells.Add(cell);

and my method look like this :

public void pic_Click(object sender, ImageClickEventArgs e) 
{
    //codehere
}

and it just doesn't work, image buttons are created and added to the table as planned, but OnClick is just not doing it's job.. I also tried adding event like this :

pic.Click += pic_Click; 

but it's the same. Just to say, I am not doing this in Page_Load method.

1
  • Can you verify you are actually firing a click event? Can you use this same event binding successfully on a static element? Commented Jan 19, 2014 at 1:49

2 Answers 2

2

You should take care of you dynamic controls during the PreInit event of the Page, as it says here.

You mentioned you're not doing it in the Page_Load, I assume you're doing it at a later point. If you follow the guideline above, your button's click event handler will run.

Sign up to request clarification or add additional context in comments.

1 Comment

if you can help me just a little bit more, i read the link you've sent me, but i don't quite understand what it is i am supposed to do? All my dynamic controls are created depending of what user chooses, how can i re-create them in PreInit event ?
0

Why don't follow this format? .aspx

<asp:ImageButton ID="ImageButton1" runat="server" Height="100px" ImageUrl="~/Images2/addtocartbutton.jpg" Width="250px" OnClick="ImageButton1_Click" />

.aspx.cs

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.