How to pass event to method?

Posted by tomaszs on Stack Overflow See other posts from Stack Overflow or by tomaszs
Published on 2010-04-01T12:27:01Z Indexed on 2010/04/01 12:53 UTC
Read the original article Hit count: 245

Filed under:
|
|
|

I would like to create a method that takes as a argument an event an adds eventHandler to it to handle it properly. Like this:

I have 2 events:

public event EventHandler Click;
public event EventHandler Click2;

Now i would like to pass particular event to my method like this (pseudocode):

public AttachToHandleEvent(EventHandler MyEvent)
{
    MyEvent += Item_Click;
}

private void Item_Click(object sender, EventArgs e)
{
    MessageBox.Show("lalala");
}

ToolStripMenuItem tool = new ToolStripMenuItem();
AttachToHandleEvent(tool.Click);

Is it possible or do I not understand it good?

Edit: I've noticed with help of you that this code worked fine, and returned to my project and noticed that when I pass event declared in my class it works, but when I pass event from other class id still does not work. Updated above example to reflect this issue.

What I get is this error:

The event 'System.Windows.Forms.ToolStripItem.Click' can only appear on the left hand side of += or -=

© Stack Overflow or respective owner

Related posts about c#

Related posts about events