tags:

views:

2282

answers:

2

I'm trying to use a single event handler for several controls in an ASP.NET web page. I would like to add the event handler at runtime if and only if it doesn't already exist. In C#, I would write it as seen below:

if (myTextBox.OnTextChanged == null) myTextBox.OnTextChanged += DoTextChangingValidation;

Likewise, I know I can remove the event handler as follows:

if (myTextBox.OnTextChanged != null) myTextBox.OnTextChanged -= DoTextChangingValidation;

I know how to add and remove the event handler in VB...I just can't seem to figure out how to check to see if it is already assigned.

+1  A: 

You don't need to do the check in vb for this scenario. The normal remove syntax is smart enough not to throw an exception at your if it's already gone.

Joel Coehoorn
+4  A: 

You cannot do that from outside the object, either in C# or in VB. An event is basically two accessors: add and remove. This is immediately visible if you hand-code it:

public event EventHandler Click
{
     add { ... }
     remove { ... }
}

These become add_Click(EventHandler) and remove_Click(EventHandler) methods. Even if you use default event implementation:

public event EventHandler Click;

it's still no different, only the accessors are generated for you with default implementation, which uses a private multicast delegate field with the same name as event to store those handlers.

This means two things:

  1. For clients of the class, the only two things they can do about an event is add or remove handlers, since only accessors are exposed. There's no accessor to list currently registered handlers

  2. Even if you use default implementation for events, which provides a field, that field is still private, so you can't access it except from inside a method of the same class. You can use reflection if you have code permission to do so, but see #1 for why it's not a general solution.

This is actually done on purpose. The reason is this: the object may be shared, and other code may have registered its handlers for its events. If you get access to list of handlers, you'd be able to call them yourself, potentially breaking the contract, and accessing private methods in a manner the owner of the class did not intend.

If you want this kind of thing, it needs to be done in the class providing the event - either write your own add and remove to check for dupes, or expose the private field via a property.

Pavel Minaev
Thank you for the clear explanation.
Michael