How to handle events of controls created at run time?

Discussion in 'ASP .Net Building Controls' started by Lalit, Dec 22, 2004.

  1. Lalit

    Lalit Guest

    Hi,

    My application has two methods which creates buttons at runtime. In one
    method I am able to handle the events of the buttons created at run time, but
    in other I am not.

    The code structure is as follows:

    page_load
    {
    ...Do something
    CreateFirstSetOfButtons()
    }

    private CreateFirstSetOfButtons()
    {
    // Create first set of buttons
    for { i=1; i<5; i++)
    {
    LinkButton newButton1 = new LinkButton();
    newButton1.Click += new EventHandler(this.Button1_Click);
    }
    ... Do something
    }

    // Event handler of first set of buttons. The second buttons are created on
    click of first buttons click.
    private void Button1_Click(object sender, System.EventArgs e)
    {
    CreateSecondSetOfButtons();
    }
    private CreateSecondSetOfButtons()
    {
    // Create first set of buttons
    for { i=1; i<2; i++)
    {
    LinkButton newButton2 = new LinkButton();
    newButton2.Click += new EventHandler(this.Button2_Click); // This event
    is never getting fired.
    }
    ... Do something
    }

    private void Button2_Click(object sender, System.EventArgs e)
    {
    Response.Write("Hello");
    }

    On click of buttons created at page load I am able to catch the Click evet
    of those buttons and the second set of buttons gets created. But when I click
    on this second set of created buttons, the statement
    Response.Write("Hello"); never gets executed.

    An early resolution for the same will be really helpful.

    Regards
    Lalit
     
    Lalit, Dec 22, 2004
    #1
    1. Advertisements

  2. Hi Lalit,

    You can't create controls in response of a click event and expect these
    controls to work ok on a postback. You need to create these controls earlier
    so ASP.NET can find them in the control tree before getting to the event
    firing stage. If you don't do this, when the event firing logic fires your
    controls have not been created yet so i.e. there is no one to handle events.
    Take a look at the docs regarding the page lifecycle to get a good grasp of
    what fires when.

    --
    Victor Garcia Aprea
    Microsoft MVP | ASP.NET
    Looking for insights on ASP.NET? Read my blog:
    My blog: http://clariusconsulting.net/vga
    My profile: http://aspnet2.com/mvp.ashx?vga
     
    Victor Garcia Aprea [MVP], Dec 23, 2004
    #2
    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.