Reputation:
I'm curious about the pros and cons when subscribing to event handlers.
<asp:DropDownList id="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" />
vs
protected void Page_Init(object sender, EventArgs e)
{
this.DropDownList1.SelectedIndexChanged += new EventHandler(DropDownList1_SelectedIndexChanged);
}
Upvotes: 0
Views: 758
Reputation: 1508
One difference is in compile time checking. If you use the declarative method and for some reason you change the handler method name or signature you won't know it until the ASP.NET run time processes the page. If you use the explicit binding in the code-behind then you'll get a compile time check on it. A bit more stable.
Also, some will likely argue that putting the event handlers in the markup contradicts the rules of separation of concerns. Although with ASP.NET web forms, there's still a bit of crossover unlike the discreet separation found in the MVC framework.
Upvotes: 1
Reputation: 243071
From the technical point of view, there aren't any big differences between the two, so it is a question of coding style and personal preferences. Here are a couple of points that you can consider:
In some cases you can use features such as C# lambda expressions nicely in the code-behind:
protected void Page_Init(object sender, EventArgs e) {
this.btnNext += (s1, e1) => MovePage(this.CurrentPage + 1);
this.btnPrev += (s2, e2) => MovePage(this.CurrentPage - 1);
// ...
}
Something like this can reduce the number of single-purpose event handling methods that you need to write, which should make the code-behind simpler.
However, I think that the general recommendation for simple ASP.NET applications is to use the declarative event handler binding, unless you have some good reason for not doing that (e.g. as in the example above).
Upvotes: 2