Run a routine in the parent form from the child form
Hi all
I'm just tring to learn C#, and I'm making a small project where I have two forms. I have a routine in form1, the parent, I need to run from form2 when I click on a button.
It is very easy in VB6. But.... How do I do it in C#
Thanks in advance
Re: Run a routine in the parent form from the child form
It's very easy in C#. The most important thing to remember is that C# is a 100% OO language. As such, programming objects in C# behave essentially as real-world objects do. In the real world, you can't ask your parent to do anything if you don't know who they are. You have to be told who your parent is so that you can refer to that specific person. It's the same in OOP. The parent form has to tell the child form that it is its parent. It does this by passing getting a reference to itself ('this' in C#) and passing that to the child form. The child then assigns that reference to a variable which is can then use to access it's parent.
Now, how do you pass a reference from one form to another? The same way that you pass any data from any object to another. You either set a property or apss a parameter to a method. That method may or may not be a constructor. That means that you need to define a property or a method, which may or may not be a constructor, in the child form to receive that reference and assign it to an internal variable for future use. If this particular child form will always be created by the same parent form then it is most logical to use a constructor, which prevents this child form being created without a reference to its parent.
I suggest that you read the Forms in VB.NET tutorial in my signature. The principles are exactly the same in C# and you can use one of the code converters in my signature to convert the code examples.
Re: Run a routine in the parent form from the child form
Thanks jmcilhinney. I will read the tutorial, but for now, can you give me a piece of code as an example?
Thank You