如何在页面加载中以编程方式向页面添加控件?

Laz*_*ale 5 asp.net pageload asp.net-controls

我试图从页面加载阶段后面的代码添加控件到页面,如下所示:

foreach (FileInfo fi in dirInfo.GetFiles())
{
    HyperLink hl = new HyperLink();
    hl.ID = "Hyperlink" + i++;
    hl.Text = fi.Name;
    hl.NavigateUrl = "../downloading.aspx?file=" + fi.Name + "&user=" + userIdpar;
    Page.Controls.Add(hl);
    Page.Controls.Add(new LiteralControl("<br/>")); 
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是,以下Page.Controls.Add(hl)是解释:

在DataBind,Init,Load,PreRender或Unload阶段期间无法修改控件集合.

我该怎么做才能解决这个问题?提前致谢.

Ode*_*ded 4

创建您自己的容器集合并将它们添加到其中,而不是直接添加到页面控件集合中。

在 .aspx 上:

<asp:Panel id="links" runat="server" />
Run Code Online (Sandbox Code Playgroud)

在后面的代码中(我建议使用Init事件处理程序而不是页面加载):

foreach (FileInfo fi in dirInfo.GetFiles())
{
  HyperLink hl = new HyperLink();
  hl.ID = "Hyperlink" + i++;
  hl.Text = fi.Name;
  hl.NavigateUrl = "../downloading.aspx?file=" + fi.Name + "&user=" + userIdpar;
  links.Controls.Add(hl);
  links.Controls.Add(new LiteralControl("<br/>"));
}
Run Code Online (Sandbox Code Playgroud)