如何使用C#从服务器端加载带有用户控件的多个内容占位符。
目前,我在服务器端(在page_load中)加载一个用户控件,如下所示:
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);
}我需要在我的页面中加载8个用户控件。我如何才能实现同样的目标?提前谢谢..
发布于 2010-08-20 17:27:12
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);
}
}或者,如果您希望每个占位符都有一个用户控件,您可以创建一个占位符列表,格式为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);
}
}https://stackoverflow.com/questions/3529521
复制相似问题