Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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)
{

}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top