3 Jan 2006

ASP.NET - controls created dynamically on event fail to fire their handler

Another wild goose chase, hoorah. So - I wanted to create an input control dynamically in response to a button being pressed on the same page. But I naturally wanted to handle events for the dynamically created control.

Here's how I did it:

1. Create a method e.g. LoadControl() to load the control.
2. Create the OnClick() handler for the button that initially loads the control onto the page, and wire it to LoadControl();

At this point, the control will appear in response to the OnClick() method, but will disappear again when you try to handle any further events that the control creates. This is because the control is only created in reaction to OnClick, not by the postback from the control. So....

3. Place code in the Page_Load() or OnLoad() method to call LoadControl() if certain postback criteria are met e.g. IsPostBack and detect some property of the dynamically loaded control from the postback.

4. And here's the bit that took me ages to track down - ensure you have given an explicit ID to every input of your dynamic control including buttons. Otherwise .NET will generate its own ID which may be different between requests, hence causing missed event handling.

Pretty obvious really, but I, as the Lancaster Bomber used to say, "had a cold". Ho ho ho.

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!