how to assign event handlers at run-time?

  • Thread starter Thread starter Dave R
  • Start date Start date
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
 
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.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
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
 
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.
}
 
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.
 
Back
Top