1

Experts,

I am facing one issue in Windows Application during button click.

I have two files A.cs & B.cs

In A.cs file I have a button called "Load" and when I click this button I need to trigger a function in B.cs.

To do this, I have written a Event Handler.

Common File:

public delegate void MyEventHandler(object sender, EventArgs e, string TagId);

A.cs file:

public event MyEventHandler OnTagLoad;

private void btnLoad_Click(object sender, EventArgs e) { if (OnTagLoad != null) { OnTagLoad(sender, e, runTimeData); } }

B.cs file:

HostForm.OnTagLoad += new MyEventHandler(HostForm_OnTagLoad);

private void HostForm_OnTagLoad(object sender, EventArgs e, string runTimeData) { //Do some functionalities }

Problem:

When I click the Load button the event is getting triggered for two times and if I again click the button, same event is called three times and so on....

Whenever I click the Load button the event should get fired only once. How can we acheive this in windows form.

Appreciate your help.

1
  • Please show any place in your code that call or has OnTagLoad.
    – Bit
    Commented Jul 29, 2013 at 14:22

1 Answer 1

3

Sounds like

HostForm.OnTagLoad += new MyEventHandler(HostForm_OnTagLoad);

is being called multiple times. Either move it to a location in the class which is only called once or remove the handler before adding it again like this

HostForm.OnTagLoad -= new MyEventHandler(HostForm_OnTagLoad);
HostForm.OnTagLoad += new MyEventHandler(HostForm_OnTagLoad);

(I recommend the first approach)

6
  • This approach I already have tried and did not give any luck. Commented Jul 29, 2013 at 14:06
  • You tried both methods? If so, then there's something more than what you've shown in your post causing the issue.
    – keyboardP
    Commented Jul 29, 2013 at 14:07
  • Basically I subscribe the event in the constructor of B.cs file. Is that causing the issue? Commented Jul 29, 2013 at 14:19
  • Put a breakpoint on the HostForm.OnTagLoad += new MyEventHandler(HostForm_OnTagLoad); line and see how many times it's hit.
    – keyboardP
    Commented Jul 29, 2013 at 14:23
  • I have checked with Call Stack, and it calls the constructor only once but when it goes to HostForm_OnTagLoad function, it calls the same function again and again. Now debugging more by pressing F11 key. Commented Jul 29, 2013 at 14:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.