dynamic linkbuttons event not raising - newbie

M

Matias Woloski

Hi, I am creating a custom server control, and it dynamically creates lots
of LinkButtons, and then I try to subscribe to the click event doing this:
LinkButton link = new LinkButton();
link.Click +=new EventHandler(this.MyLinks_Click);

When I then click on the link, it never invokes MyLinks_Clicks... I guess
this happens because I don't create the linkbuttons neither on
CreateChildControls() nor OnInit(). I create them depending on some input
data and some properties.
All that MyLinks(...) does is set a property to a value, depending on the
linkbutton pressed, beacuse I need it when I render again my control.
Can someone give me a hint on how to solve this problem? Maybe instead of
subscribing to the event, I can catch the name of the linkbutton that caused
the PostBack or something.
Thanks
 
A

A Traveler

Hello, i dont think your problem has anything to do with adding the OnClick
handler not in CCC or in OnInit. I have a number of pages which add dynamic
controls and bind them up to an eventhandler then and there. It doesnt
usually matter too much where you do that.

You could try checking the form postback. You would look in
Request("__EVENTTARGET") and see if it contains the name of your control.
The event handlers is definitely the better way to go though, and it should
work.
I dont know if this is just a typo or not, but in your post, you said you
add new EventHandler(MyLinks_Click), but that it never executes
MyLinks_Clicks, with an "s" on the end. Maybe that is it? or its just a
typo.
 
S

Skok Tone

You have to add control to control collection of custom control for events
to work.
 
V

Victor Garcia Aprea [MVP]

Hi Matias,

Where are you creating them? In response to a postback event? If so, then
its too late for them to fire any event at all. You need to move creation
earlier in the page lifecycle. Also, you will need to recreate the
linkbutton(s) on postback *even* if you don't need them this time in order
to get the event fired, you can then -before rendering- remove them.

--
Victor Garcia Aprea
Microsoft MVP | ASP.NET
Looking for insights on ASP.NET? Read my blog:
http://clariusconsulting.net/vga
My profile: http://aspnet2.com/mvp.ashx?vga
 

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

Latest Threads

Top