Difference OnInit and OnLoad in ASP.NET? - c#

I had an interview a week ago and one of the questions was what the difference was between OnInit and Onload in ASP.NET? I had no clue and I don't find any simple answers on the net so can someone explain shortly and simple what the difference is between both? (What I found was that the difference was somehting in the lifecycle).

OnInit (the Init event) happens after all controls have been initialized, but before ViewState tracking is enabled. It's called bottom-up (the Init events for child controls are called before their parent's Init event).
Init is a good place to add dynamic controls to your page or user control (though it's not a requirement). If you can, then those controls will have their ViewState restored automatically during postbacks (see below). It's a risky place to set control properties, though, because they can be overwritten by incoming ViewState. Init is the right place to set ViewStateUserKey, which can help protect your site from one-click attacks. You would also call RegisterRequiresControlState() from there, if you're using control state.
Right after the Init event, each control enables ViewState tracking, so any changes to a control's properties after that will be reflected in ViewState.
The next events at the page level are InitComplete and PreLoad, neither of which is visible at the control level. During a postback, incoming ViewState is restored into controls between InitComplete and PreLoad.
Then comes the Load event, which happens for both controls and the page. Load is called first at the parent level, and then for any child controls. A master page behaves like a control on a page with regard to event ordering.

You need to read up on the ASP.NET page lifecycle.
OnInit happens earlier in the lifecycle - view state changes have not been done yet and tracking of it has not been turned on.

Page_Init is raised before Page_Load. Page_Init is a good place for code that you want executed before you process further such as attaching event handlers to the load event.
it is better not to access controls in this event because you aren't guaranteed they have been created.
The Page_Load is a good place to store code where you initialize values and any controls specific to the page because you know at this point the controls exist and are available.
You will place a lot more code in Page_Load than you will in Page_Init for the majority of your apps

Both these methods of Control class are invoked by ASP.NET. OnInit() method raises the Init event and OnLoad() method raises the Load event.

Related

How can I invoke OnInit event of UserControl?

my situation is a little complicated. What I'm trying to do is make reload UserControl (with dynamically changed control inside my UserControl). It's simple when I trying to do it OnInit or Page_Init event of my Page. But I need to do this inside a click event of button which by the way is ext.net type and have build in callback events.
So is there any way to invoke OnInit event of UserControl on event click raise?
If any more information needed pls feel free to ask in comments:)
Thanks for advance:)
I think you should manage this case differently.
OnInit is fired according to the webform life-cycle, in which each step has a specific purpose :
http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
During page initialization, controls on the page are available and
each control's UniqueID property is set. A master page and themes are
also applied to the page if applicable. If the current request is a
postback, the postback data has not yet been loaded and control
property values have not been restored to the values from view state.
You'd better not 'force' this concept, try to adapt your code to meet the flow constraints.

User control losing state

I have a user control that I am explicitly calling from an aspx page. In page_load of the aspx page I have the following:
myControl = (DynamicTable)Page.LoadControl("../inc/DynamicTable.ascx");
Then in my code where I want it to execute the control, I have this:
pnlESDDEnrolled.Controls.Add(myControl);
where pnlESDDEnrolled is the panel I am loading it into for display.
So, I execute the aspx page, it links off to the user control, populates the control, returns back to the aspx page and the page displays with the user control in the middle of it. All is well.
The problem comes in when updates are made on the user control. Keep in mind, that other data is updated on the page as well, and the update button resides on the page, not the control. Anyway, when the update button is pushed, the button_click event is fired on the page, but the updates that I made on the user control are lost. Since the page loaded the user control and then the usercontrol executed the page unload method, the page has no knowledge of the user control anymore. Thus, when the update button on the page is pushed, I guess I am not really sure what happens with the updated data on the user control. All I know is that it is lost. I have been working on this for a huge amount of time, any help would be much appreciated
You need to check for IsPostBack in your user control, too.
As your page loads, the Page's Page_Load event starts, then your UserControl's Page_Load will begin, execute, then its events, then controls returns to the page's Page_Load, then all of its events. Of course, if you are using Pre_Init on the page or overriding OnInit in your controls, those events execute before the Page_Load.
So, if you are dynamically creating items on your UserControl, check for IsPostBack and places those events an override OnInit function in the UserControl. Then add your programmatic reference to that UserControl in the Page_Init of the page.
I guess while you're talking about user control state these are realised as Properties in the code?
If so, then you're probably going to have to use Viewstate to persist the UserControl's state so that when the page comes back, the UserControl will be re-populated first with what it previously had when it was being rendered. This is as simple as changing any public state properties to use ViewState as the backer.
I'm not a great fan of viewstate, but sometimes it has to be used.
However there may be more at work here - as your instincts are telling you, this might also be a problem with the fact that this usercontrol is loaded dynamically.
In which case, it all depends at which part of the page lifecycle you're doing it. You need to get this control into the page's tree before render (pre-render might be possible), as it's at this point that that page 'captures' its controls collection for the purposes of maintaining state.
Try and move the insertion of this control into the page structure as early as you can in the lifecycle. The earlier the better - so Page_load would be fine.
Equally - it might be you're already doing this - in which case I'd need more information (perhaps a reproducable scenario) in order to help fix it.

What if you want webpart communication before Page_Load?

I am needing to create some dynamic controls at Page_Load in the consumer webpart. In the Provider webpart I did some hacking and got it so I could get a controls value before viewstate is loaded in Page_Init.
So basically what I want is for webparts to be able to communicate before Page_Load.
[ConnectionConsumer("FormRID Consumer","FormRIDConsumer")]
public void InitializeProvider(MyControl.IFormRID provider)
{
theProvider = provider;
FormRID = theProvider.FormRID;
}
That method doesn't get called until after Page_Load. This is a big problem for me because my consumers Page_Load depends on FormRID being set and accurate. I can't move my Page_Load code into Page_LoadComplete either because I am needing to create dynamic controls with viewstate(viewstate isn't restored after Page_Load)
So is there some work around I can use so that I can communicate before Page_Load.
Have you tried subscribing to the web part zone's Init event and placing your InitializeProvider() there? I believe it is fired before OnLoad or OnInit events of user controls and web forms.
You should use on OnPreRender event instead of on Load, beause onLoad occurs before WebPart connection executes.
Here is one example of what you could expect using OnLoad and OnPreRender events http://blog.mastykarz.nl/web-part-requires-clicking-twice-apply-ok-button-apply-changes/
I ended up having to create my own webpart communication.
It ended up much cleaner than ASP.Net's and communication can happen as early as OnInit inside of the webparts.

Should I add control event handlers programmatically within Page_Init?

I want to add event handlers programmatically to the server controls rather than using their predefined OnClick properties, etc. But which would be considered a better practice for defining handlers:
Define them in Page_Init
Define them in Page_Load
...and why?
Page_Init
Everything that has to be maintained between page cycles should be declared in Page_Init, not Page_Load.
edit All the initialization, like adding event handlers, and adding controls should be added during initialization, as the state is saved between page cycles. Handling with the content of controls and the viewstate, should be done in Load.
Check also http://msdn.microsoft.com/en-us/library/ms178472.aspx.
Init
Raised after all controls have been initialized and any skin
settings have been applied. Use this
event to read or initialize control
properties.
.
Load
The Page calls the OnLoad event method
on the Page, then recursively does the
same for each child control, which
does the same for each of its child
controls until the page and all
controls are loaded.
Use the OnLoad event method to set
properties in controls and establish
database connections.

How To Make A Web User Control's Child Control's Events Cause A Catchall Event To Fire On The Parent Once Per Postback

Say that I have a web user control that has several drop down lists in it. They are all set to AutoPostBack = true, BUT each SelectedIndexChanged event handler in my control will fire/chain the other SelectedIndexChanged handlers I have defined for the other DDLs. This means that when the user changes a single DDL, the event handlers are chained/fired for several other DDLs. The logic for which events are chained is very complicated, data driven, and can change depending on which list was actually changed by the user. Therefore, it is very difficult to determine which event handler would fire last.
From the page's point of view, I want to subscribe to a single SelectionChanged Event on the user control that will only fire one time per postback and not until all of the event handlers have fired. I don't care which event handlers have fired, only that the state of the control as a whole has changed.
I'm using C# 3.5/ASP.NET 2.0/VisualStudio 2008
How can I go about doing this?
EDIT: Moved clarification into original description. I think the fact that I specified AutoPostBack=true without specifying that chaining was happening was misleading. I apologize for the confusion.
It depends on when you need the event handler to fire in the page lifecycle.
Here's one strategy:
1) In your user control, track the selection changing of your dropdown lists. If the event handler is executed, update your local tracking variables.
2) In your usercontrol's PreRender handler, check your tracking variables and if called for, fire the user control's SelectionChangedEvent.
This strategy will guarantee that the event handling phase of the page lifecycle is done, but has the drawback that your main page won't receive the "SelectionChanged" on your user control until the PreRender phase. This may or may not work for your situation.
If you need to handle the SelectionChanged event for your usercontrol earlier, then you will likely have to put in more complicated tracking logic in your dropdownlist handlers, and add a tracking variable to ensure that the usercontrol's "SelectionChanged" event only ever gets fired once.
I think you need to create a delgate in child control and then reference that delegate into parent control.

Categories

Resources