In 3 years at PSS I've worked on many issues related Dynamic Control i.e

1) Controls not able retain value on postback.

2) Controls getting disappeared on postback

3) Event handler not fired on first click works fine on second click

4) Viewstate issues blah blah...

 

No matter how complex the issue maybe I got it resolved by sticking to following silver bullet point

  • Always add the dynamic control in Page_PreInit()
  • Always assign ID when loading dynamically

For Example

protected void Page_PreInit(object sender, EventArgs e)
{
        Control c= LoadControl("./WebUserControl2.ascx");
        i=i+1;
        c.ID= i.ToString();
        PlaceHolder1.Controls.Add(c);
}


OR

protected void Page_PreInit(object sender, EventArgs e)
{
         LinkButton button1 = new LinkButton();
         button1.ID = "button1"
         button1.Text = "button1"
         PlaceHolder1.Controls.Add(button1);
}

 

This way it would make sure Dynamic Controls are added to Page Control tree and ID's are not messed up.

Tip: Best way to troubleshoot is to enable trace=true at page level and track that particular control id's or compare view source for first time page rendering with view source on page postback.

Hope it helps Winking