Dave Mateer
Dave Mateer

Reputation: 6636

WinForm event subscription to another class

public partial class Form1 : Form
{
    private EventThrower _Thrower;

    public Form1()
    {
        InitializeComponent();
    }

    private void DoSomething()
    {
        MessageBox.Show("It worked");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        _Thrower = new EventThrower();
        //using lambda expression..need to use .NET2 so can't use this.
        _Thrower.ThrowEvent += (sender2, args) => { DoSomething(); };

        var eventThrower = new EventThrower();
        eventThrower.test();
    }
}

public class EventThrower
{
    public delegate void EventHandler(object sender, EventArgs args);
    public event EventHandler ThrowEvent = delegate { };

    public void SomethingHappened()
    {
        ThrowEvent(this, new EventArgs());
    }

    public void test()
    {
        System.Threading.Thread.Sleep(1000);
        SomethingHappened();
    }
}

I'm trying to get my winform UI to subscribe to an event in EventThrower class. DoSomething never fires.

How to subscribe to other class' events in c#?

Upvotes: 1

Views: 1199

Answers (2)

Ed Swangren
Ed Swangren

Reputation: 124790

The event is not static, one instance of the EventHandler exists for each instance of EventThrower.

You subscribe to the event on _Thrower, yet you create a new instance of EventThrower and call test() on that instance. You never subscribed to the event on that instance, so your handler doesn't run.

It should be:

_Thrower.ThrowEvent += (sender2, args) => { DoSomething(); };
_Thrower.test();

Upvotes: 1

competent_tech
competent_tech

Reputation: 44971

This is because you create a new EventThrower before calling test.

If you change:

    var eventThrower = new EventThrower();
    eventThrower.test();

to:

    _Thrower.test();

It will call DoSomething.

Upvotes: 0

Related Questions