Adding events to dynamically created 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 ?
 
S

S. Justin Gengo

Jez,

When you add dynamic controls to a page you have to re-create them on every
page load in order for their events to fire.

I have some samples of dynamic control use on my web site,
www.aboutfortunate.com. I think they may be good for you to look at. Just
click the code library link on the top right of the page and then enter
"dynamic control" or something similar in the search box and you'll get all
the relevant code.


--
Sincerely,

S. Justin Gengo, MCP
Web Developer / Programmer

www.aboutfortunate.com

"Out of chaos comes order."
Nietzsche
 
J

JezB

ah - true

I was thinking that the event(s) fired before the page posted back, but I
guess it's the other way round.
 

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,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top