views:

112

answers:

1

how to load multiple content placeholders with user controls from server side using C#..

currently from serverside(in page_load) i am loading one usercontrol like this:

ContentPlaceHolder cph = this.Master.FindControl("TopContentPlaceHolder") as ContentPlaceHolder;
UserControl uc = this.LoadControl("~/webusercontrols/topmenu.ascx") as UserControl;
if ((cph != null) && (uc != null))
{
    cph.Controls.Add(uc);
}

I need to load 8 usercontrols in my page. How can i achieve the same? Thanks in advance..

A: 
string[] listOfControls; //initialize as you will
ContentPlaceHolder cph = this.Master.FindControl("TopContentPlaceHolder") as ContentPlaceHolder;
for (int i=0; i<listOfControls.Length; i++)
{
   UserControl uc = this.LoadControl(listOfControls[i]) as UserControl;
   if ((cph != null) && (uc != null))
   {
       cph.Controls.Add(uc);
   }
}

or in case you want one user control per placeholder you can create a list of placeholders as vell

string[] placeholders;
string[] listOfControls; //initialize as you will

    for (int i=0; i<listOfControls.Length; i++)
    {
       ContentPlaceHolder cph = this.Master.FindControl(placeholders[i]) as ContentPlaceHolder;
       UserControl uc = this.LoadControl(listOfControls[i]) as UserControl;
       if ((cph != null) && (uc != null))
       {
           cph.Controls.Add(uc);
       }
    }
Constantin
Hi Constantin..thanks for the solution..it helped me alot...
karthik