ASP Developer Network - Brought to you by Steve Radich and BitShop, Inc. - http://www.bitshop.com

Menu [hide]

ASPFaqEventsDoubleFire

My Events are fired twice? Page_Load gets processed twice for example print
similar comment

My Events are fired twice?!


Server Event Handling in Web Forms Pages


First let me apologize, this was initially submitted by a non-English as a native language contributor, I (Steve Radich) quickly went over it to try to phrase things better, but there are still a few confusing points. I hope you find this information useful, if there are mistakes I need to correct please contact us and we will re-review this article.

Introduction


Most web forms have events, events require a round trip to the server for processing, they can affect the performance of the server and the form if the events are processed slowly. It may be a little tricky to handle events. You may have problems where events aren't occuring when you expect, or even they may be run twice. The following short info about events and event handling hopefully will help you better understand this.

Intrinsic Event Set


Server controls offer a limited set of intrinsic events, usually only click-type events. Some server controls support a special version of the onchange event, which is raised when the control's value changes. For example, the asp.net Form control can raise an onload event when the form is loaded, or, the CheckBox Web server control can raise a change event when the user clicks the box.

Event Delegates in Web Forms Pages


An event is a message — is something like "a button has been clicked". In your application, you want the message to be translated into a method call in your code, such as "Button1_Click". The binding between the event message and a specific method — that is, an event handler — is done using an event delegate. For more information on how this works see the links at the bottom of the page titled MSDN: Events and Delegates.

In ASP.Net you typically do not need to explicitly code delegates. If you use the Web Forms Designer in Visual Studio, the designer generates code that automatically binds events to methods. In Visual Basic, this can be done using the Handles keyword in the event handler declaration, as in this example:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load


In Visual C#, the designer generates an explicit event-handler delegate in the page, similar to the following:

private void InitializeComponent()
{   
   this.Load += new System.EventHandler(this.Page_Load);
}


Alternatively, the ASP.NET page framework also supports an automatic way to associate page events and methods. Unless the AutoEventWireup attribute of the Page directive is set to false (it's true by default), the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.

The disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names - However use caution if NOT using these names as someone else viewing your code may be confused initially by trying to track these things down. The AutoEventWireUp can be viewed as limiting your flexibility in how you name your event handlers however. If you disable the AutoEventWireup attribute the designer generates explicit code to bind page events to methods.

If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

Setting up both methods will cause a problem


What will happen if you create a simply page with one control on it, similar to this:

<%@ Page Language="VB" AutoEventWireup="true"  CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<body>
    <form id="form1" runat="server">
   <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />&nbsp;</div>
    </form>
</body>
</html>


Then you will specify codebehind, similar to this:

Partial Class Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
        Response.Write(Now() & "<hr/>")
    End Sub

End Class


After run it, you’ll get one Now time string.

Then if you try to add an Event Delegates Button1.Click to Button1_Click Sub, as you see below:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Response.Write(Now() & "<hr/>")
    End Sub


After run it, you’ll get a page with two(!) time strings on it!
As you see, OnClick method will execute twice. It is true in VB.NET and also C#.NET.

As we know, Anders Hejlsberg, the creator of C#, always makes a strong point of not adding a new feature to the C# language when it will open the possibility to do the same thing on two different ways, because that could be confusing. This feature is more than confusing. Two very different ways to get the same thing done: one in a directive and one in "normal"code. And both ways hide the fact that you are not assigning one specific method as a handler for an event. The same method can even subscribe twice to the same event. Like just we demonstrated above.

It will affect mantaining your Datagrid or anything else, where you handle events.

So please keep this in mind and make sure you don't wire up your events twice - For some things it may not be obvious, but for more intensive or long running operations you may end up doubling the load or time your event takes to respond.

Related Links:


Eugene,
Bitshop.com


Created by: steveradich last modification: Friday 03 of November, 2006 [03:04:13 UTC] by steveradich



Search
in:
Our Sponsors
Quality Business Internet Technology Shop - http://www.bitshop.com Sponsor of site and hosting
Latest Virtual Server 2005 R2 News
www.virtualserverfaq.com/ng
Quality Business Internet Technology Shop - http://www.bitshop.com Sponsor of site and hosting
Latest Virtual Server 2005 R2 News
www.virtualserverfaq.com/ng
Latest Virtual Server 2005 R2 News
www.virtualserverfaq.com/ng
rss Wiki rss Blogs rss Articles rss Image galleries rss File galleries rss Forums rss Maps rss Directories
ASP Developer Network (since 1996) - Brought to you by Steve Radich and BitShop, Inc. - http://www.bitshop.com
Copyright © 1997-2005 by BitShop, Inc. All Rights Reserved.
No content may be reproduced in any form without written permission from BitShop, Inc.
We will be honored to assist with reproduction rights on our material if you contact us.
We also can provide print articles for your magazine, private training seminars at your site, and conference presentations.

Thank you for visiting. Please bookmark our site if you found it useful!
If you wish to make a donation it will help further the development of these free resources: