1
votes

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

1 Answers

3
votes

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)