I would suggest you to switch visibility instead of loading dynamically. That'll make things a lot easier.
On this way you don't need to
- recreate the controls on postbacks
- store the number of created controls somewehere
- take care of lifecycle issues(f.e. no events triggered etc) when creating controls too late
- etc...
Remember: Visible="False"
does also mean that it will not even exist on client-side as html, so you don't need to be afraid of creating unnecessary traffic.
Rule of thumb: Create controls in ASP.NET dynamically only when the number of controls is unpredictable on compile time.
But even if it's unpredictable because you get this information from dbms you should consider to use a Data-Bound Control instead(f.e. GridView
or Repeater
).
So only a few use cases remain where you need dynamical controls, for example
- the user can add/remove controls temporarily and you don't want to store the number in dbms but in
Session
or ViewState