954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Any good tutorials on Events and Delegates?

Hello. I've seen some tutorials, but I can't find one that particularly suits my needs.

What I'm trying to do is this: I have a form that contains an object. I want this object to be able to modify its parent form when an event for it is thrown. The problem is that this object does not have a reference to the form's fields. Where can I find a nice, beginner-friendly tutorial that provides a sample that's easy to reproduce in a large application?

Thanks.

SoftwareGuy
Light Poster
26 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

Check the following links...
1st link , 2nd link , 3rd link , 4th link , 5th Link , 6th link , 7th link , 8th link .... Hope they will help you

abelLazm
Postaholic
2,113 posts since Feb 2011
Reputation Points: 219
Solved Threads: 124
 
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Child c = new Child();
            c.MyEventHappened += new Child.MyEvent(c_MyEventHappened);
        }

        void c_MyEventHappened(int i)
        {
            textBox1.Text = "My event happened";
        }
    }

    class Child
    {
        public delegate void MyEvent(int i);
        public event MyEvent MyEventHappened;

        public Child()
        {
        }

        public void DoSomething()
        {
            //I've finished doing something I should let anyone who cares know
            MyEventHappened(1);
        }

    }

That should be basically what you need to do. The Child class has a delegate called 'MyEvent' with a specific signature. Then the Child class has an event called 'MyEventHappened" which uses MyEvent. So, when 'MyEventHappened' is called in 'DoSomething' anything attached to 'MyEventHappened" will also be called. And if you look in the 'Form1' class in the constructor 'c_MyEventHappened" is wrapped in the 'MyEvent' delegate and added to the 'MyEventHappened' event.
Make all the stuff in your child class first. Then go back to your form and attach to the event. Just a heads up, in Visual Studio when you type '+=' after referencing an event, it will automatically offer to write the code for you. Keep in mind that the signature of the delegate is up to you.

kimbokasteniv
Junior Poster in Training
50 posts since Nov 2006
Reputation Points: 13
Solved Threads: 4
 

@abel: I like the first and last two links. Provide great insight.

@kimbo: A highly simplified example and what I ended up following.

Thanks a lot for the help, guys.

SoftwareGuy
Light Poster
26 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: