How to add control to the page programatically in page load?

孤人 提交于 2020-01-03 13:45:29

问题


I am trying to add controls to the page from the code behind in the page load stage like this:

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

The error which I am getting is on Page.Controls.Add(hl) and here is the explanation:

The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

What can I do to fix this issue? Thanks in advance.


回答1:


Create your own container collection and add these to it, instead of directly to the page controls collection.

On .aspx:

<asp:Panel id="links" runat="server" />

In code behind (I suggest using the Init event handler rather than page load):

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



回答2:


Add your controls into Init() event of Page.



来源:https://stackoverflow.com/questions/4484854/how-to-add-control-to-the-page-programatically-in-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!