Question

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";
    }
Was it helpful?

Solution 2

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().

OTHER TIPS

If you must create your button dynamically, create it inside the OnInit() method of the page.

Event handling happens after Page Init. So, the button will have to be created before Page Init, for the events to be handled.

The button goes out of scope mate. define it as a private variable otherwise the event wont fire as the button disposed after Selected_floor_first method finishes

private Button btn = new Button();

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

protected void room_1_Click(object sender, EventArgs e)
{
        validation.Text = "You selected a Room";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top