C#•Add Controls Into the PlaceHolder Control

Listing 3. AddControls() iterates through the BasePage object's control collection and adds controls into a PlaceHolder control contained within the BasePage object by calling another method named AddControl() (see Listing 4). You remove controls from the Page object's collection as you add them to the BasePage.

private void AddControls(PlaceHolder content) {
   Trace.Warn("Start Add Controls");
   int count = _Controls.Count;
   int i  = -count;
   try {
      while (i < count) {
         Control currentControl = 
         _Controls[0];
      if (currentControl is HtmlForm) {
         int childCount = 
            currentControl.Controls.Count;
         int j = -childCount;
            while (j < childCount) {
            Control child = 
            currentControl.Controls[0];
            AddControl(child,content);
         currentControl.Controls.Remove(child);
            childCount = 
               currentControl.Controls.Count;
            j++;
            }
         }
         else {
            AddControl(currentControl,content);
         }
         _Controls.Remove(currentControl);
         count = _Controls.Count;
         i++;
      }
   }
   catch (Exception exp) {
      content.Controls.AddAt(0,
         new LiteralControl("error occurred: 
            " + exp.StackTrace));
   }
   Trace.Warn("End Add Controls");
}