Thursday, September 26, 2013

Dynamically Created Control Not Firing Events in ASP.Net

I have an aspx page where when someone changes the value in a Drop Down List the database is queried and records are displayed in an HTML table.  As the table is created I add a Button control to each row.  I have tried this with a CheckBox as well with similar results.  I also wire up a click event for each button when it is created.  All the events for the Buttons point to the same event.

The grid is created properly, with the button on each line.  When I click one of the buttons the Page_Load event fires, but the click event does not.

When I dynamically create a button outside the grid from the Drop Down List's SelectedIndexChanged event it also does not fire the click event.

When I move the button creation code to the Page_Load event wrapped in an If (!IsPostback) block the Click event works properly.

It appears that if the control is not created in Form_Load or Form_Init the dynamic control's events do not fire.  I have not found a solution to be able to do what I want, but I thought what I found in my research so far might be useful to someone.