Valid for Sitecore 5.1.1
Add a sublayout programmatically

Sitecore versions: tested with 5.1.1.21. Expected to work with 5.1.1.x.

The Problem

Our code needs to add a sublayout programmatically.  

1.  The Solution

Use the code below to solve the problem:

protected void Page_PreInit(object sender, EventArgs e)

{

     Database db
= Factory.GetDatabase("master");

     Item slItm
= db.Items["/sitecore/layout/sublayouts/Test"];

     Sublayout sublayout
= new Sublayout();

     sublayout.Path
= slItm["Path"];

     sublayout.DataSource
= db.Items["/sitecore/content/home"].Paths.Path;

     MainPH.Controls.Add(sublayout);
//Placeholder on the page

}

Note: The LayoutPageEvent setting should be set to load in web.config.