Click event handler not called on dynamically create image button

R

rh.krish

Hi,
I'm have a web form where I generate templates dynamically based on
the user input. When the user clicks the 'create' button I create a row
dynamically and create an ImageButton dynamically in that row. I also
tie the onClick event to a server side event handler, but when I click
the dynamically created ImageButton, the postback occurs, but the event
handler is not called. Here is what my code looks....

private HtmlTableCell CreateTableCell ( HtmlTableRow row, int
controlID, .......)
{
HtmlTableCell cell = new HtmlTableCell ( "td" );
ImageButton btnPlus = new ImageButton ();
btnPlus.ImageUrl = "images/plus.jpg";
btnPlus.ID = controlID; // id dynamically generated by the caller
and passed to this method
btnPlus.Click += new System.Web.UI.ImageClickEventHandler (
this.btnPlus_Click );
cell.Controls.Add ( btnPlus );
}

private void btnPlus_Click ( object sender, ImageClickEventArgs e )
{

// call some method....
}

Help is appreciated.

Regards,
Hari.
 
P

Phillip Williams

Hi Hari,

The problem you described is a common problem in creating controls
dynamically. Here are a few guides that might help you correct the problem:

1) Dynamically created controls should be created during or prior to the
Page Initialization phase to maintain their ViewState upon postback. The
following links give more in depth information about the control’s lifecycle.

http://msdn.microsoft.com/library/d...guide/html/cpconcontrolexecutionlifecycle.asp

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaspp/html/viewstate.asp


2) In the case where you have to load the control late within the page
lifecycle (e.g., while responding to another server control event) then save
in the Session a variable (or a simple class with few attributes) that allows
you to recreate the dynamic control within the Init event handling upon
postback.

I have a demo to demonstrate the concept on this link:
http://www.societopia.net/Samples/DynamicallyCreatedControls.aspx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top