views:

34

answers:

3

In doing a lot of ASP.NET pages (.NET 2.0), my codebehind is typically packed with event handlers on page objects. GridView_RowCommand, Button_Click, etc. All the usual suspects. One thing all EventHandler derived things have in common is that their first argument is an object, typically labeled "sender".

In ASP.NET codebehind, I really don't see the point of it. If I have GridCustomers_RowCommand and I need to do something to GridCustomers, I can just access it from the codebehind instead of worrying about casting sender to a gridview and then working with it.

I feel like I must be missing a very important design consideration here. Am I doing something stinky to my code? I kind of can see that using direct references this way is falling prey to global objects, but that's just how ASP.NET works! What am I not seeing here? Is there some superb book or tutorial that shows how to use ASP.NET the "right way?" The clean, agile, "real coder" way?

+1  A: 

Yes, if you have an event handler that is called by several controls, and you need to know which control called the event handler.

It seems like a backwards way to do it, but it can eliminate repeated code if the event handler is the same for most controls, except for a few minor differences.

That said, I've only ever seen it in real code once, and I thought it hurt readability. I like to have one event handler per control/event.

David Stratton
+5  A: 

You might have one event handler for DRY coding, yet 20 things that use that event, for example:

protected void AddClass(object sender, EventArgs e) {
   ((WebControl)sender).CssClass += " myNewClass";
}

In this case you're writing the code once, but it can be used by many WebControls (this is an example, the point is not specific to WebControls at all).

Disclaimer: Do I use sender every day? no not even close, is it useful? yes it can be :)

Nick Craver
With the extra disclaimer, I think that's a pretty good, comprehensive answer. I hadn't considered the case of multiple controls using it, but that could be very handy for like a gridview or a repeater. Also, I'm glad to know I'm not the only person who just uses the control names directly! I feel much better now.
CodexArcanum
+1  A: 

The sender parameter of an event signature is provided so that you can establish the context of the event.

This is useful say, if you have several nested controls in an ASP.NET control hierarchy, whereby they are all executing the same event handler for a specific event, the sender parameter allows you to distinguish between the different controls.

Sometimes, the subclassed EventArgs parameter provides the context for you in a neater fashion, sender is still useful for abstract event handlers.

Rabid