c# - Why does Message Box appear twice when event is called. -


so i've been following visual studio tutorials microsoft has available (more math quiz 1 found @ https://msdn.microsoft.com/en-us/library/vstudio/dd492172.asp)

but deviated bit tutorial because wanted see if create event , call using eventhandler delegate though might not best solution.

public event eventhandler quizstarted;  

here code creating event.

now in method

 public form1()     {         this.quizstarted += new system.eventhandler(this.showthatthequizstarted);         initializecomponent();     } 

i have initialized event instance of eventhanlder points showthatthequizstarted method.

public void showthatthequizstarted(object sender, eventargs e)     {         messagebox.show("quiz has started");     } 

and when start button pressed call quizstarted event shown below.

    private void startbutton_click(object sender, eventargs e)     {         startbutton.enabled = false;          quizstarted(this, new eventargs());          this.startthequiz();      } 

in order message box goes away after hitting okay once, in startthequiz() nothing calles message box directly or indirectly.

but if place this.quizstarted += new system.eventhandler(this.showthatthequizstarted); line startbutton_click method, message box appears twice 1 right after other.

though found solution know why happens if place line of code out of constructor.

if...

this.quizstarted += new system.eventhandler(this.showthatthequizstarted); 

... gets called multiple times, happen if move inside button click event handler method, in fact adding , registering new event handler every time.

in other words, when quizstarted invoked, may call multiple event handlers, depending on how many choose register. if register same event handler multiple times, called many times.

that's why want leave registration in place guaranteed register event handler once , once.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -