Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi I know i am lazy but just to check if there is any better ideas around.
I had an event in a usercontrol
C#
public event EventHandler EH_OpenDefaultClick;


A form when a radio button is click will subscribe to this event. However this form will not be destroyed and whenever the radio button is click, i will subscribe to the event
C#
ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;


with the only line above, every time it will be subscribe, hence triggering multiple time. I can add in the code to compare if it is null. But eventually codes get untidy with all these == null

C#
if (ucStdButton_Recipe.EH_OpenDefaultClick == null)
    ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;


I cannot declare the event as static as the event is subscribe during runtime. Is there any declaration type allowing me to subscribe more easily without the comparison statement
Posted

You can check for a specific handler subscription:

C#
public bool IsHandlerSubbed(Delegate handler)
{   
	if ( this.EventHandler != null )
	{
		foreach ( Delegate h in this.EventHandler.GetInvocationList() )
		{
			if ( h == handler)
			{
				return true;
			}
		}
	}
	return false;
}
 
Share this answer
 
You can prevent it by unsubscribing before adding it:
C#
ucStdButton_Recipe.EH_OpenDefaultClick -= ucStdButton_Recipe_EH_OpenDefaultClick;
ucStdButton_Recipe.EH_OpenDefaultClick += ucStdButton_Recipe_EH_OpenDefaultClick;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900