How to add page control to a page soft loading?

I am trying to add controls to a page from code located at the page loading stage, as follows:

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 I get is on Page.Controls.Add(hl)and here is the explanation:

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

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

+5
source share
2 answers

Create your own collection of containers and add them to it, and not directly to the collection of page controls.

On .aspx:

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

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

Init() .

0

All Articles