Custom Event is getting called multiple times

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.


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)

链接地址: http://www.djcxy.com/p/6068.html

上一篇: C#Interop执行后不关闭Excel进程

下一篇: 自定义事件被多次调用