I am developing a win form app and I found myself constantly requiring to access methods in my parent form say Form1 from another class be it a form class or just a class. I
The way that I normally do this is to have the child form expose events corresponding to the logical actions and events on that form, for example:
/// <summary>
/// Occurrs when an item is selected in the form
/// </summary>
public event EventHandler<ItemSelectedEventArgs> ItemSelected;
/// <summary>
/// Fires the <see cref="ItemSelected" /> event
/// </summary>
protected void OnItemSelected(MyItem item)
{
var handler = this.ItemSelected;
if (handler != null)
{
ItemSelectedEventArgs args = new ItemSelectedEventArgs();
args.Item = item; // For example
handler(this, args);
}
}
The idea is that the logic of your parent form should respond to actions on your child form, rather than actions on your child form driving actions on the parent form - you should try to encapsulate the forms logic as much as possible (aka separation of concerns).
Also as a pattern it should be the parent / calling form that handles marshalling the calls across to the correct thread via InvokeRequired
etc... rather than the child form - this will be unneccessary anyway unless you are doing work on background threads.
Your class should raise events and your form should have the event handlers. This keeps your form code in your form and your class code in your class. Nice and neat.
Raising events, as suggested by Kragen and Richard will work, and stops the parent/child relationship from being as tightly coupled, but if you want something really flexible, look into the Event Aggregator pattern. There is a nice one provided in the Prism project here, although a lot of people find it inconvenient to use, and have created extensions in order to make it easier to work with such as this, or written their own from scratch such as this.
Basically, the idea is that the parent doesn't even care that the message came from its child window. The child window has merely thrown a message such as "Open Order #6" onto the message bus, assuming that someone else will handle it, pretty much the same as raising an event. Elsewhere, the parent form, which is responsible for containing all the child forms has subscribed to "Open Order" messages, and so it receives the message, and opens a new child window for Order #6.
Since the parent isn't directly "welded" to the child anymore, it's possible for these messages to originate elsewhere as well, now. You could raise "Open Order" messages from a most-recently-used list on the parent form itself, or in reaction to a hyperlink in some other form being clicked. It no longer matters who asked for order #6 to be opened, only that someone did. It's a highly flexible model that eliminates a lot of tight coupling.