1

What is the correct event/method in the ASP.NET life cycle to dynamically add Child Controls ?

My objective is to ensure that all the input controls on a User Control have the correct associated Validator and Label controls, based on configuration from an external file.

It seems like the correct place should be either OnInit(EventArgs e) or CreateChildControls(). Both of them are behaving a little bit unexpected, and rather than try to debug each of them, I figured I'd first ask you guys which one (or other) to use.

smartcaveman
  • 41,281
  • 29
  • 127
  • 212
  • Care to explain the issues your having? – asawyer Sep 30 '11 at 12:53
  • @asawyer, I've been moving stuff around trying to figure it out. So far, I've gotten an `OutOfMemoryException` (making me think there I was causing an infinite loop), a "Multiple controls with the same ID 'dynamicallyAddedRequiredFieldValdiator' were found" (making me think I put it somewhere that caused the routine to be called twice), a "Collection was modified, enumeration may not execute" error and a "The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.". – smartcaveman Sep 30 '11 at 12:57
  • Is this a custom server control, or a web user control (ASCX)? – James Johnson Sep 30 '11 at 15:13
  • @James, it's a web user control, However, if there is a difference with respect to this distinction please specify, thank you! – smartcaveman Sep 30 '11 at 15:47

2 Answers2

2

Its OnInit, and you need to do it on first load and on post back.

Sprintstar
  • 7,938
  • 5
  • 38
  • 51
  • So, I call the routine ALWAYS OnInit, and also ALWAYS on PostBack ? Or do I call it from OnInit and make sure it is either (a) the first load or (b) a postback. Can you be a little more specific? – smartcaveman Sep 30 '11 at 12:58
  • If you put your code in `OnInit`, it will be called every time the page is posted - first, last, and every postback in between. – James Johnson Sep 30 '11 at 15:12
  • @smartcaveman - Create your control in OnInit, and do it on every call, eg don't check for postback. – Sprintstar Oct 04 '11 at 09:32
1

Since this is a Web User Control (ASCX) create the dynamic controls during OnInit. By creating them during OnInit they will be created on the first page load and on every postback.

The CreateChildControls method is typically used for rendering in custom server controls.

James Johnson
  • 45,496
  • 8
  • 73
  • 110