load multiple content placeholders with user controls from server side using C#
-
30-09-2019 - |
Question
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..
Solution
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);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow