Should I add control event handlers programmatically within Page_Init? - c#

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.

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.

Difference OnInit and OnLoad in ASP.NET?

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.

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.

How to get the value of usercontrol in codebehind of page

How to get the value of usercontrol to page holding usercontrol?
If I understand correctly, the problem is that you are trying to access the user control's StudentId property in page_load of the page that hosts the user control?
If that's the case, it is quite likely that you are just trying to read the data before the user control has fired the SelectedIndexChanged event on the dropdown list.
The simplest solution is to move the code that reads the property to the Page_PreRender event. This event happens late in the page life-cycle, and after all the user events have had a chance to fire off.
As an alternative, you can expose your own event (I'll call it "UserControlDropDownChanged") in the user control and have the code in your SelectedIndexChanged event handler fire the user control's UserControlDropDownChanged event. In your page, during page_load or page_init you'd register an event handler to listen to UserControlDropDownChanged from the user control... and in that event handler perform whatever functions you need to when the drop down list's value changes.
I provided an example of how to use events this way in response to another question here on SO if you aren't familiar with this technique.
You'll need to expose this value as a public property of the user control.

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