How to test if EventHandlers have been added to an event

S

Steve Richter

no sure of the terminology ... would like to test if an EventHandler
has been added to an event:

if (this.Load == null)
{
this.Load += new EventHandler(RowPrompt2_Load);
}

foreach (EventHandler xx in this.Load)
{
}

compile error:
The event 'System.Web.UI.Control.Load' can only appear on the left
hand side of += or -=

how do I test that
this.Load += new EventHandler(RowPrompt2_Load);
has already been run?

thanks,

-Steve
 
M

Marc Gravell

In this case (with "this"), perhaps the better solution in to override
OnLoad?

protected override void OnLoad(EventArgs e) {
// your code here
base.OnLoad(e);
}

With events : simple; keep track of what your code is up to... perhaps
keep a boolean for the purpose.
Another trick is to unsubscribe first; this has no effect (if you
aren't already subscribed) on most implementations - i.e.

this.SomeEvent -= handler;
this.SomeEvent += handler;;
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

you cannot with that construction. All you can do is Add/Remove them

What you can do though is declare the event using the "real" way and keep a
list of the added handlers, then you could implement a method like:

List<EventHandler> list;

EventHandler _ev
event EventHandler ev
{
add{ list.Add( value); _ev += value;}
remove{ list.Remove( value); _ev-=value;}
}

bool IsAttached(EventHandler e)
{
foreach(EventHandler ev in list)
if (ev == e)
return true;
return false;
}


Please note that I typed the above text in OE, so it might not compile the
way it;s
 

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