user1151923
user1151923

Reputation: 1872

C# creating event handler 'method name expected' error

So I have a class made specifically for holding an event handling method which I want to use in multiple other classes:

class MyHandler
{
    public MyHandler()
    {
    }

    public void Method1(object sender, EventArgs e)
    {

    }
}

Now if i do:

button1.Click += new System.EventHandler(this, MyHandler.Method1);

I get the error mentioned in the title. What am I doing wrong here?

Upvotes: 3

Views: 4818

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499770

It's not clear what your arguments are meant to be for. If the event subscription code is within an instance method of MyHandler you just want:

button1.Click += new System.EventHandler(Method1);

or more briefly:

button1.Click += Method1;

If it's from a different class, you either need to create an instance of MyHandler, e.g.

MyHandler handler = new MyHandler();
button1.Click += handler.Method1;

or make the Method1 method static and subscribe like this:

button1.Click += MyHandler.Method1;

Upvotes: 6

Stecya
Stecya

Reputation: 23266

Use this

class MyHandler
{
    public static void Method1(object sender, EventArgs e)
    {

    }
}

button1.Click += MyHandler.Method1;

Upvotes: 3

Related Questions