0

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..

Timwi
  • 65,159
  • 33
  • 165
  • 230
karthik k
  • 3,751
  • 15
  • 54
  • 68

1 Answers1

1
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
  • 465
  • 4
  • 18