Responding to events in dynamically created web controls

J

JezB

I'm adding WebControl objects to a Page dynamically on Page_Load, but I'm
having trouble attaching events to these. For example, adding an image
button :-

ImageButton nb = new ImageButton();
nb.ImageUrl = "text.gif";
nb.ToolTip = "Edit Text";
nb.Click += new ImageClickEventHandler(b1_Click);
myPlaceholder.Controls.Add(nb);

(myPlaceholder is a Placeholder object added to the Page at design time)

private void b1_Click(object sender, ImageClickEventArgs e)
{
// etc
}

Problem is, on clicking the button the event is not fired at all - it just
forces a postback - what am I doing wrong ?
 
J

Joe.Dattilo

The Server Side Event Handling happens before the page_load event and after the On_init ... add your controls and event handler hookups in the On_Init Event and you should be able to get the events to fire.

Joe
 
R

Robert Koritnik

This is OF COURSE NOT true. All events happen AFTER Page_Load event. The
thing is, that you developers sometimes don't know how the process happens
in the first place.
All dynamic controls should be restored the same way they were created the
first time. And you have to recreate them BEFORE the events get processed.
So the latest possible time to recreate those is Page_Load.
What JoeDattilo suggested is the way to process ViewState, not events.
Because viewstate gets processed after OnInit and BEFORE PageLoad. If you
don't need that, then forget about it...

--
RobertK
{ Clever? No just smart. }

Joe.Dattilo said:
The Server Side Event Handling happens before the page_load event and
after the On_init ... add your controls and event handler hookups in the
On_Init Event and you should be able to get the events to fire.
 

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

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top