0

I am in the phase of testing the project and I am dealing with a problem with attaching an event handler multiple times to the button.

I have a class with the _btnSelecteProj field, which I assign the button reference via the parameter in the InitProjects method.

Public Void InitProjects (Button btnSelectProject)
{
        _btnSelecteProj = btnSelectProject;
        _btnSelecteProj.MouseClick += BtnSelectProj_MouseClick;
}

This method is in the runtime called several times and therefore the event handler is assigned multiple times, which I need to prevent.

I realize that this a wrong design. However, it is not possible to refactor the whole project, because I am in a testing phase. I struggle with this problem in several places in the code.

I tried to prevent this problem this way:

_btnSelectedProj.MouseClick -= BtnSelectProj_MouseClick;
_btnSelectedProj.MouseClick += BtnSelectProj_MouseClick;

But it doesn't work.

I appreciate any advice.

cooper538
  • 1
  • 1

3 Answers3

0

In your event you can implement the add/remove operations as explicit methods and check you event handler for null in add.

  • The problem is that I work with the system class Button, so I can't affect these modifiers – cooper538 Nov 26 '19 at 09:00
  • Can [this](https://www.codeproject.com/Questions/205627/How-to-detect-if-one-eventhandler-is-null-or-not) solution help? – Michael Mankiewicz Nov 26 '19 at 09:13
  • Thanks:) I suppose not, as it is written in the link: **Checking up if the event instance is null is impossible outside the class declaring the event.** Thats my case. – cooper538 Nov 26 '19 at 09:56
0

For example you can check if the value of _btnSelecteProj is changed

public void InitProjects(Button btnSelectProject)
{
    if (_btnSelecteProj != null)
    {
        if (_btnSelecteProj.Equals(btnSelectProject))
            return;
        _btnSelecteProj.MouseClick -= BtnSelecteProj_MouseClick;
    }
    _btnSelecteProj = btnSelectProject;
    _btnSelecteProj.MouseClick += BtnSelecteProj_MouseClick;
}
Michael Navara
  • 1,111
  • 2
  • 8
  • 13
0

I had to add method ClearEventHandlers() and remove event handler proper way.

public void ClearEventHandlers()
{
    _btnSelecteProj.MouseClick -= BtnSelectProj_MouseClick;
}

This method runs at the end of the object's life-time.

NOTE: I'm not sure whether this question/answer is useful to someone else...

cooper538
  • 1
  • 1