Tuesday, May 26, 2009

(Probably not) the last word on Dynamic ASP.Net Controls

Dynamic ASP.Net controls are always a mystery to me.

That is, they always seem to be pretty straightforward but whenever I implement them I find things not going quite according to plan, and then spending a couple of days getting everything right. And then, a year or so later when I next need to implement them, I've forgotten everything and make the same mistakes again. Rinse and repeat.

The most common mistake, although one that I know well about so don't struggle with, is the question of when to create the controls. You need to create them on the Page_Init event so that the controls get into the page lifecycle early enough. This can sometimes lead to headaches as occasionally the decision as to what controls require creation isn't naturally resolved until Page_Load, but then you just need to be resourceful.

The problem that I do have, however, is events. Frequently I create dynamic controls in Page_Init, but when those controls trigger an event, the event doesn't fire.

Now, I'm not 100% sure of the details of the cause and effect link here, but after today's exploratory I can confirm that the fix for this is to ensure that whilst your controls need to be created and added under Page_Init, they should not be initialized until Page_Load.

This may well be a situational issue, but a problem that I've had lately with a button on a subcontrol not firing when added dynamically vanished when I simply split the creation logic from the initialization logic, and moved initialization to Page_Load and under a (if !Page.IsPostBack).

Will continue exploring, but when - in 2 years time - I'm next dabbling with dynamic controls, I hope I remember to read this first :)

No comments: