I use a base page object (named Web.UI.Page) that overrides the Render(HtmlTextWriter w) method. Today I was working in a unique situation where I wanted to add a user control (UserSideBar.ascx) to the sidebar above the existing control (SideBar.ascx). At first I created a new base page called UserPage. I found myself re-overwritting the entire Render method. I played around and made a RenderHeader and RenderFooter, which I think I'll keep, but the meat of the page was still having to be overriden.
Then I got to thinking, what could I do to add it to the existing Page object. ControlCollections came to my mind. Sure enough, they work great.
First I added my Collection to the page:
public System.Collections.ArrayList SideBarControls = new System.Collections.ArrayList();
Then in my Page's Render method I added:
Control SideMenu = LoadControl("~/Controls/SideMenu.ascx");
SideMenu.ID = "SideMenu";
this.SideBarControls.Add(SideMenu); // Put the side menu in there
foreach(Control c in this.SideBarControls)
{
Controls.AddAt(++x,c);
}
++x is just a integer that helps add the controls incrementally. Yeah it's cheesy, but it works great.
Now in my Default.aspx page that I want to add the extra sidebar control I simply add:
this.SideBarControls.Add(LoadControl("~/Controls/UserSideMenu.ascx"));
It adds the control just above the existing sidebar...which is exactly what I needed to do, yipee! I might just add this type of functionality to each section of the page, then I could add controls at certain points based on what aspx page I'm viewing...hmmm.