views:

89

answers:

4

I want to add more controls to page based on some specific conditions. Those controls don't need any ViewState or binding data, it is as simple as a static link. I wonder where I could write the code: inside OnLoad or OnInit method? and why? If I place it inside OnLoad, should I add following line: if (IsPostBack) return; before any initialization code?

+1  A: 

I would suggest just adding the controls to the page statically and toggling their visibility to "True" when the conditions are met. They won't render anything to the page when they're invisible, and this will save you a lot of headaches, especially since it sounds like you're fairly new to dynamic controls.

womp
A: 

I'm not sure I fully understand, but I'd personally put an asp:Literal on the page (or several if you need them in different places) and then create the HTML you need in the OnLoad event.

If you do that, then the html you put into that literal will be saved in viewstate, and therefor you won't have redo it on postback.

Matt Dawdy
+1  A: 

You can add controls in either the OnInit method or OnLoad, whether they need view state or not. (The reason why is because as soon as you add a control to the Page the control loads its view state, even if you add it after the LoadViewState stage...)

should I add following line: if (IsPostBack) return; before any initialization code?

No. It is imperative that your dynamically added controls are added to the control hierarchy on every page load, not just the initial one.

If you are going to work with dynamically-added Web controls, I strongly suggest you read these two articles:

For a working, end-to-end example of dynamically loading controls based on some external conditions (such as configuration in a database), see Creating a Dynamic Data-Driven User Interface.

Happy Programming!

Scott Mitchell
A: 

http://chetanwarade.wordpress.com/2010/08/21/asp-net-add-dynamic-control-and-retrieve-dynamic-control-value-2/ Here is code that demonstrate how to add dynamic control and retrieve dynamic control value.

chetan