Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically add an event handler in VB.NET if it doesn't exist

Tags:

vb.net

events

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 Visual Basic... But how do I figure out how to check to see if it is already assigned?

like image 385
Michael Avatar asked Dec 30 '22 12:12

Michael


2 Answers

You cannot do that from outside the object, either in C# or in Visual Basic. 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 the default event implementation,

public event EventHandler Click;

it's still no different, except that the accessors are generated for you with the default implementation, which uses a private multicast delegate field with the same name as the 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.

like image 197
Pavel Minaev Avatar answered Jan 01 '23 02:01

Pavel Minaev


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

like image 34
Joel Coehoorn Avatar answered Jan 01 '23 01:01

Joel Coehoorn