Wednesday, February 10, 2010

Always wire your events in the code behind, NOT in the aspx/ascx template file

With ASP.NET you can wire your events in the aspx/ascx template file or in the code behind file. If you wire your events in the template file, you will not get compile time support. This means that if a method is renamed or removed without updating the template file, the compiler will not throw an error. However, if the event is wired in the code behind, an error will be thrown. Events should therefore always be wired in the code behind.
Template file event wiring - not recommended:
<asp:Button runat="server" ID="BtnSave" OnClick="Save" Text="Save" />
Code behind event wiring - recommended:
protected override void OnInit(EventArgs e)
{
 base.OnInit(e);

 BtnSave.Click += new EventHandler(Save);
}