0

如何使用 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 个用户控件。我怎样才能达到同样的效果?提前致谢..

4

1 回答 1

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);
   }
}

或者如果您希望每个占位符有一个用户控件,您可以创建一个占位符列表作为 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);
       }
    }
于 2010-08-20T09:27:11.820 回答