C#, How to create an event and listen for it in another class?

c#, winforms

Solution

Step 1) Expose an event on MainForm... say..

public event Action simpleEvent

Step 2) Give MyUserControl a constructor that takes an instance of MainForm and bind an action to that event

public MyUserControl(MainForm form) {
    form += () => Console.WriteLine("We're doing something!")
}

Step 3) raise the event in MainForm.Button_Click

if(simpleEvent != null) simpleEvent();

Note: You could register your own delegates and work with something other than lambda expressions. See http://msdn.microsoft.com/en-us/library/17sde2xt.aspx for a more thorough explanation

Your end result would look like...

public Class MainForm : Form
{
    public event Action MyEvent;

    MyUserControl MyControl = new MyUserControl(this);
    private void Button_Click(object sender, EventArgs e)
    {
        if(simpleEvent != null) simpleEvent();
    }    
}

public Class MyUserControl : UserControl
{
    //listen for MyEvent from MainForm, and perform MyMethod
    public MyUserControl(MainForm form) {
        simpleEvent += () => MyMethod();
    }

    public void MyMethod()
    {
         //Do Stuff here
    }
}

Problem

I can't figure out how to do this, heres sample code. Of what I wish to do. ``` public Class MainForm : Form { MyUserControl MyControl = new MyUserControl; private void Button_Click(object sender, EventArgs e) { //Create MyEvent } } public Class MyUserControl : UserControl { //listen for MyEvent from MainForm, and perform MyMethod public void MyMethod() { //Do Stuff here } } ```

Original source