Eventhandler question

  • Thread starter Thread starter Broeden
  • Start date Start date
B

Broeden

Hi,

Probably an easy question.

I need to add and remove EventHandlers for different controls. The
problem is how do i prevent an eventhandler from being added twice.

This is not working

if (ctrl.GotFocus == null)
ctrl.GotFocus += new
System.EventHandler(cboHkl_GotFocus);

I'm used to Delphi before, there I had tested with"if
assigned(ctrl.GotFocus)"

How is this done with C#?

/Broeden
 
If you are constantly subscribing/unsubscribing to a external event, simply
unsubscribe like the following:

ctrl.GotFocus -= new EventHandler(cboHkl_GotFocus);

Testing for null can only be done in the class that implements the event.
 
Thanks!

It's a bit complicated. In a quite big existing code I'm replacing
ctrl.Enable = false with an event handler that denies focus. This
because I can't live with the light gray color of the font when
Enable = false. As a result of this the eventhandler might have been
added more then one time when I need to remove it.

That why I have to ensure I don't add a second eventhandler to the
same control. Overall the same event routime is used by about 30
controls.

/Broeden
 
Sorry when I wrote add and remove eventhandlers I ment subscribe and
unsubscribe to an eventhandler.
/Broeden
 
Why not just create a custom control that has this behavior? That way you
don't need to do all of the adding/removing of handlers except in the
control code itself.
 
Problem solved!

I let all the controls subscribe to the eventhandler. Then I use the
Tag property to set if the control shall deny focus of not. Works
perfect!

/Broeden
 
Back
Top