how to assign event handlers at run-time?

Discussion in 'ASP .Net' started by Dave R, Mar 17, 2005.

  1. Dave R

    Dave R Guest

    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
     
    Dave R, Mar 17, 2005
    #1
    1. Advertisements

  2. Dave R

    Brock Allen Guest

    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 Allen, Mar 17, 2005
    #2
    1. Advertisements

  3. Dave R

    Karl Seguin Guest

    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
     
    Karl Seguin, Mar 17, 2005
    #3
  4. Steve C. Orr [MVP, MCSD], Mar 17, 2005
    #4
  5. Dave R

    Karl Seguin Guest

    Karl Seguin, Mar 17, 2005
    #5
  6. Dave R

    Matt Berther Guest

    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.
    }
     
    Matt Berther, Mar 17, 2005
    #6

  7. 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.
     
    Steve C. Orr [MVP, MCSD], Mar 17, 2005
    #7
  8. Dave R

    Matt Berther Guest

    Hello Steve C. Orr [MVP, MCSD],

    Oh dear... Here we go... ;)
     
    Matt Berther, Mar 17, 2005
    #8
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.