Search code examples
c#asp.net.netautopostback

Button created after PageLoad - Click Event not firing


I have a button that is created after a user selects a certain value from a dropdown menu, but it is not firing its' EventHandler. Is there something with the Lifecycle, OnInit possibly, that I have to refresh for the handler to fire correctly?

Event fired from DropDownList's OnSelectedIndexChanged

protected void Selected_floor_first(object sender, EventArgs e)
{
    Button btn = new Button();
    btn.ID = "room_button_1";
    btn.Text = "Select";
    btn.Click += new EventHandler(room_1_Click);
    floor_1_room_overlay.Controls.Add(btn);
}

Handler: (Not Firing)

protected void room_1_Click(object sender, EventArgs e)
    {
        validation.Text = "You selected a Room";
    }

Solution

  • As it is dynamically added, you have to take that code in Page_Init() event that occurs after every postback. otherwise when the postback occurs, there is no room_button_1 in the forms.controls collection and the event is missed. So

    1. add it as it is being added.
    2. after adding set a variable in session to identify that dynamic control has been added
    3. on page_init() check the session variable of step2. if it says yes then create the control you created in step 1.

    Instead of repeating the code, it's better if you create a function for button creation and call it from your Select_floor_first() and Page_Init().