Wednesday 7 August 2013

How to use the AutoEventWireup attribute in an ASP.NET

We can specify the default value of the AutoEventWireup attribute in the following locations:

1. The Machine.config file.
2. The Web.config file.
3. Individual Web Forms (.aspx files).
4. Web User Controls (.ascx files)

If you make these changes in the Machine.config file, the changes affect all ASP.NET Web Forms on the computer. If you make these changes in the Web.config file, the changes affect only the application that the file belongs to. However, to make changes in the individual Web Form Only, we have to add the AutoEventWireup attribute to the @Page directive.

AutoEventWireup will have a value true or false. By default it is true in C#.NET and false in VB.NET.

Generally when you request a webpage page the page life cycle begins.

AutoEventWireup ="true"

If you set the AutoEventWireup to true VisualStudio will generate the code to bind the events and then page events will call based on their names.

public class EventWireUpFalse : System.Web.UI.Page
    {
      private void Page_Load(object sender, System.EventArgs e)
      {
Response.Write("The Page_Load Event Fired with AutoEventWireup False");
      }
   }
 
In the above code the Page_Load event called directly.

AutoEventWireup = "false"

If you set the AutoEventWireup to false Visual Studio will not be able to generate code to bind the events. In this case, you must define explicit Handles clause or delegate.

public class EventWireUpFalse : System.Web.UI.Page
    {
      private void Page_Load(object sender, System.EventArgs e)
      {
Response.Write("The Page_Load Event Fired with AutoEventWireup False");
      }  
      // adding a new delegate to call the Page_Load event.
      override protected void OnInit(EventArgs e)
      {
         this.Load += new System.EventHandler(this.Page_Load);
      }

   }

In the above code Page_Load method will call through the delegate.

No comments: