How To Test For Assigned Event Handler

R

Ratfish

Hi,

I'm trying to test whether an event handler is already assigned to a
TextBox's TextChanged event handler before I assgn it. When I use the
following code I get the "The event
'System.Web.UI.WebControls.TextBox.TextChanged' can only appear on the
left hand side of += or -=" error.

if (tbxQuantity.TextChanged == null)
tbxQuantity.TextChanged += QuantityTextChanged;

I don't want to assign the even handler if it's already been done.
Please help.

Aaron
 
P

Peter Duniho

Ratfish said:
Hi,

I'm trying to test whether an event handler is already assigned to a
TextBox's TextChanged event handler before I assgn it. When I use the
following code I get the "The event
'System.Web.UI.WebControls.TextBox.TextChanged' can only appear on the
left hand side of += or -=" error.

if (tbxQuantity.TextChanged == null)
tbxQuantity.TextChanged += QuantityTextChanged;

I don't want to assign the even handler if it's already been done.
Please help.

Fix your code/design so that you don't need to check the event to see
whether it's already been assigned.

There are some past discussions in this newsgroup (you can Google Groups
the newsgroup to find them) related to the question of inspecting the
event. The short answer is: an event is strictly an "add" and "remove"
method as far as any code outside the declaring class is concerned.
Only the declaring class has access to implementation details, like the
currently subscribed delegates.

In those past discussions, there are some examples of scenarios where it
makes sense for _some_ code to inspect the event, and those always wind
up being a matter of the declaring class providing some sort of
functionality (and in some of those cases, the "declaring class" winds
up being a sort of event-proxy class wrapping the class where the
original event is actually declared).

But in your own situation, the idea that your own code would
conditionally subscribe to an event based on whether there's already a
delegate subscribed to it or not, that sounds like a very fragile and
unwise design to me. Your own code's decision to subscribe should not
depend on whether or not any other delegate has already been added to
the event.

Pete
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top