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. 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)

Sign up to request clarification or add additional context in comments.

6 Comments

This approach I already have tried and did not give any luck.
You tried both methods? If so, then there's something more than what you've shown in your post causing the issue.
Basically I subscribe the event in the constructor of B.cs file. Is that causing the issue?
Put a breakpoint on the HostForm.OnTagLoad += new MyEventHandler(HostForm_OnTagLoad); line and see how many times it's hit.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.