best practice when dealing with dynamic control issues

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");
        c.ID= i.ToString();


protected void Page_PreInit(object sender, EventArgs e)
         LinkButton button1 = new LinkButton();
         button1.ID = "button1"
         button1.Text = "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

Comments (2)

  1. vijeta says:

    hi.. m doin d same.. but wen m publishing the site in IIS 6.0 and accessing it .. my dynamic controls appear n disappear in less than a sec… how ever i knw thy r thr cos i can still get their values .. plzzzzzz help m almost dead wrkin on dis

Skip to main content