When to wire up event handlers asp.net - c#

Let's say we have a pretty standard form with a textbox and a button (for simplicity). You want to handle a Click event and do some stuff based on user's input.
I was wondering, does it matter, when exactly you wire up an event handler for the Click event in a code-behind? If it does, where is the best place to put it? Page load? Page init? I've tried both places, but didn't notice any difference. Or it's just a personal preference of the programmer? I've already searched the internet couple of times, but haven't found any satisfactory answer.
I know when the actual method execute, just not sure about the wiring-up part.

As you know, there are several Page_xxx event handlers, like Init, Load, Prerender... This events exist in Controls, and Pages as well as User controls (in fact they're derived form Control, which holds all these events).
This events are related to the ASP.NET Page Life Cycle
If you read the page pointed to by this link carefully you will understand when the events are triggered. So, if you bind your event handler in any page lifecycle event that happens before the events are triggered, it's guaranteed that your event handlers will be bound in time to be triggered.
These are the main lifecycle steps:
PreInit -> Init -> InitComplete -> PreLoad -> Load -> [Control events] ->
LoadComplete -> PreRender -> SaveStateComplete -> Render -> Unload
Not all of them have associated events, but, if it's necessary you can override the corresponding OnXxx() function, like OnPreInit(). (This is usually only done on custom server controls).
You can bind events in Page_Init or Page_Load, because the control events are triggerd after the loading of all the controls has finished. The Load step happens in top-bottom way, first in the Page, and then recursively in all the children controls.
After Load finishes, the first events which are triggered are the Change Events, like TextChanged or SelectionChanged. Then are triggered all the other events, like Click.
If you bound the events in PreRender or Unload, they wouldn't be triggered. If you did in Init or Load, they would.
So it could look like it's safe to bind in Init or Load, but that's not true:
It could look like there's no special reason to bind them on Init or Load, because they'll be triggered later in the page life cycle. But, as the binding defined in the .aspx happens during Init, a programmer will expect that all events are already bound in the Load event. What would happen if this programmer raised an event of a child control in code behind? The Load event happens first in the root of the control tree, and them on all of the children, recursively. So, by the time the programmer is trying to raise the event of the child control, it won't be already bound. So this won't work as expected. This is more than enough to consider unsafe to bind events in Load event. That's why you should always bind events in Init.
Look at this diagram to see the order of execution of Page & children events:
ASP.NET Page Life Cycle Diagram

I have been wiring mine up in the control tag. If I do it this way it is clear that an event handler is present.
<asp:Button ID="btnRefresh" runat="server" Text="Refresh" OnClick="btnRefresh_Click" />
If I had to wire up an event handler in the codebehind, I would put it in Page_Load as a private function call.

Related

When to remove event handlers from an object?

So I am registering some event handlers in an object's loaded event.
tv.PreviewMouseDown += new MouseButtonEventHandler(SignalScrollViewer_PreviewMouseDown);
but I had two questions.
If loaded occurs twice and it tries to add the event handler again will there be problems?
How should I handle unregistering the event? Will it automatically handle unregistering on destruction or do I need to handle it in some event like unloaded or something?
Yes that will cause another subscription which causes the handler to execute twice. You can remove the loaded handler inside the loaded handler.
MSDN:
Loaded and Unloaded might both be raised on controls as a result of user-initiated system theme changes. A theme change causes an invalidation of the control template and the contained visual tree, which in turn causes the entire control to unload and reload. Therefore Loaded cannot be assumed to occur only when a page is first loaded through navigation to the page.
If the object is gone it cannot raise any events, so no need to do anything about that. And the handler will not keep the object alive (it's the other way around).
If loaded occurs twice and it tries to add the event handler again will there be problems?
The event will get subscribed multiple times. You may want to handle this scenario.
How should I handle unregistering the event? Will it automatically handle unregistering on destruction or do I need to handle it in some event like unloaded or something?
You can unregister it in Unloaded or similar. In general, you only need to do this if object on which the event you're subscribing will live beyond your lifetime. If it's an object within yourself (ie: subscribing to an event on a button within a user control, from the user control), unsubscription isn't required.
One normally subscribes to events from inside the constructor, i.e. immediately after the tv object gets created. If you keep those together, it's not possible to subscribe multiple times to the same tv object.
One would want to register event handlers in Loaded and remove them in Unloaded, so any objects which handle the event would have a defined lifetime. So, one would wish that every Loaded event occurs only once when the control is shown, and is followed by an Unloaded event when the control is removed from sight.
However, Loaded might be raised several times, depending on your layout: Expander causes Loaded to be raised twice, but Unloaded only once on controls inside the Expander, and TabControl might reuse the same controls for different TabItems (different data) without raising Loaded or Unloaded in between.
I found two ways to get around this: Either use DataTemplates (this helps at least in the TabControl case), or use the DataContextChanged event to register / unregister the events, which is a good way to ensure that the object which receives the events is always the current DataContext (i.e. ViewModel).
You might also want to check out the following link for more information on attaching and removing event handlers and other behaviours: http://wpfglue.wordpress.com/2009/12/11/the-sticky-component-framework/

Dynamically added ASP.NET button click handler being ignored

I am adding event handlers to a button like this:
btn.Click += new EventHandler(btn_Click);
However the btn_Click function is not being called (never hits the breakpoint in it) and the button just reloads the page. In my past experience, asp buttons usually perform the click code before reloading the page, so how do I get that to happen when the event is dynamically added?
I also set CausesValidation = false, although there's no validation on the page so I don't think that would have influence anyway.
The event handler needs to be bound for every request regardless of whether or not the page is being posted back. The binding of the event handler is lost at the start of each page request. Event handlers for buttons are typically bound in Page_Load.
You have to set event handlers on Load event (or before). If you do it after Load, it won't be executed since by the time the handler for the event is evaluated it won't be there.
Check this msdn article in relation to page life cycle. I think it will help you to understand. See that event handling occurs inmediatly after Load

Loading ASP.NET user control at run time

I have an ASP.NET user control with a button, and I want to add it to the page when the user clicks a button from another user control. I have created an event handler to the first user control to handle it from the page and add the second user control to a page. Everything is working normally, but the button on the second user control doesn't respond to the event.
I place the second control on RadAjaxPanel
Note: When I add the second user control at design time its working fine.
All dynamically created controls should be added by the end of Page_Init (though sometimes you can get away with them added by the end of Page_Load).
If you're only adding them based on a button click event then you've done this in the event handers which fire AFTER Page_Init and Page_Load in the lifecycle - This is why your events don't fire and why it works fine when you add at design time.
This is because when a button is clicked on the second user control - the whole page lifecycle starts again. The page goes through Page_Load and Page_Init first and your control doesn't get loaded here. So, when the page lifecycle handles the "handle postback events" part, the control no longer actually exists, so the event doesn't fire.
Conversely, when you add at design time, the control exists in Page_Init and Page_Load so is able to handle the postback events from the user control because it already exists in the control tree - if this makes sense.
You need to think how you can restructure so they're added by the time Page_Load has finished at the very latest or it won't work. Without code samples or more detail it's hard to suggest exactly how you might do this. One possibility would be to set it visible instead of loading it outright - but if the control does some 'heavy lifting' on load like database hits or API calls then this might not be suitable for you.
I did something similar. What I did was to load some controls dynamically based on a selection from a DropDownList. If you have a method which loads the control for you, let's call it LoadControls(), then you can do something like this:
DropDownList_Click {
ViewState("LoadControls") = true;
LoadControls()
}
By setting the ViewState variable, you can then indicate Page_Load to load the controls on future postbacks:
Page_Load {
if (ViewState("LoadControls") == "true")
{
LoadControls();
}
}
This has the effect of then loading the control on-the-fly when the event first happens, and then at future times in the lifecycle.

page/control lifecycle

I have usercontrol x in a page, within usercontol x is usercontrol z. I need to do something to usercontrol z after an event fires in usercontrol x. I understand this is very generic, but it just lays out a simple premise for my issue.
Is there a simple way to get a list of all events that fire in the page lifecycle whether I am subscribed to them or not to find out what events fire between Event A on the page and Event B on control z? I would think that there would be something like this when page tracing is turned on, but I don't see any events listed. I imagine that it would be something that the pipeline could generate, maybe I could use reflection to get a list?
I found this topic hard to search against in general, maybe I am using bad keywords...
I did find an old project on codeproject.com, but I was hoping that there would be something more elegant available by now.
*To clarify, I'm looking to generate a list after a postback of every potential event (subscribed or not), in firing order from init to unload, of all controls on a page.
THIS POST: Tracing all events in VB.NET
gets me a little bit closer, however these are lists on a per control basis, not in chronological order.
Enable trace with <%# Page Trace="true" %> in page attribute. that should display life cycle events in sequence.
Well if you're just looking to see what the events are in general, and in what order they fire, check out this article. As far as getting them...well, that depends on what you mean. It could be as simple as getting them through reflection:
EventInfo[] events = this.GetType().GetEvents();
The ASP.NET Page Life Cycle Overview on MSDN lists all of the events fired by a Page from PreInit to Unload. Most of these events fire on any class that inherits from System.Web.UI.Control as well.
Update
Now that I understand your intention better, one possible solution would be to loop through the events of every control and assign an event handler that logs the calling of the event. There is at least one way to retrieve all of the event handlers assigned to an event, and it shouldn't be too difficult to adapt that code to assign an event handler instead.

Interesting ASP.NET Lifecycle Event Firing Error

I'm having an interesting lifecycle event error, imagine a code hierarchy like this:
Page 1
User Control 2
User Control 3
Where each of these items is a child in this order. I expect Page 1 to fire its oninit first, then User Control 2, then User Control 3. But this doesn't happen; actually, in this scenario, User Control 3 fires init first. I have each of these inheriting from a special base class, and have some plumbing code that needs to run in order. Any idea why this is happening?
Thanks.
What you're seeing isn't an error. It's happening because that's the way it's supposed to happen:
The Init event of individual
controls occurs before the Init
event of the page.
As pointed out by others, the Init events fire from the bottom up, while later events (such as Load) fire from the top down.
The general rule for how events are raised is that the initialization events are raised from the innermost control to the outermost one, and all other events are raised from the outermost control to the innermost one.

Categories