3

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?

4 Answers 4

7

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!

Sign up to request clarification or add additional context in comments.

1 Comment

AFAIK, for populating a static control, you only need to populate on the initial page load if the relevant code is in Page_Load. However, if the code is in OnInit you need to populate on every page load.
1

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.