how to assign event handlers at run-time?

D

Dave R

Anyone know how to wire up an event handler for controls added to an ASP.NET
page at run-time? Of course, at design-time this is easy: just enter the
method's name in the event tab of the control's properties. But what if I
do...

LinkButton lb = new LinkButton();
lb.Text = "Click me now!";
cell.Controls.Add(lb);

I want to create a handler for lb's Click event, like...
lb.Click = "MyHandler";
....but that syntax is illegal. When you click the button, it properly posts
back, but I can't infer in Page_Load() the reason (i.e., the originator) of
the action. Can't find anything in the on-line docs about this. Any ideas?

Thanks,
:-David
 
B

Brock Allen

Do you want a client-side event or a server-side event? For a client-side
event:

lb.Attributes.Add("onclick", "alert('hello')");

For a server-side event, you'll have to read the docs on what events are
supported by which controls. A Label doesn't have a [server-side] Click event,
but a Button does.
 
K

Karl Seguin

lb.Click += new EventHandler(lb_Click);

private void lb_Click(object sender, EventArgs e) { ... }

just be aware that dynamically created/added controls must be
recreated/added on postback in Page_Load (or earlier) in order for their
postback event to hook...

Karl
 
M

Matt Berther

Hello Dave,

LinkButton lb = new LinkButton();
lb.Text = "Click me now!";
lb.Click += new EventHandler(lb_Click);

private void lb_Click(object sender, EventArgs e)
{
// whatever you want to execute when the link button gets clicked.
}
 
S

Steve C. Orr [MVP, MCSD]

Karl Seguin said:
He's using C# ;)

Karl


Oh, well that's his problem right there!

;)

If he were using VB.NET he could use syntax that was actually intuitive,
such as the Handles keyword or AddHandler.
 

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,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top