views:

212

answers:

3

Hi, I am quite new to windows forms. I would like to know if it is possible to fire a method in form 1 on click of a button in form 2? My form 1 has a combobox. My form 2 has a Save button. What I would like to achieve is: When the user clicks on Save in form 2, I need to check if form 1 is open. If it is open, I want to get the instance and call the method that would repopulate the combo on form 1.

I would really appreciate if I get some pointers on how I can do work this out. If there any other better way than this, please do let me know.

Thanks :)

Added: Both form 1 and form 2 are independent of each other, and can be opened by the user in any order.

A: 

Of course this is possible, all you need is a reference to Form1 and a public method on that class.

My suggestion is to pass the Form1 reference in the constructor of Form2.

Gerrie Schenck
Gerrie, I am not calling form 2 from form 1, so I dont think I can pass reference. Form 1 and 2 can be opened by the user in any order. Is it still possible?
Rashmi Pandit
A: 

What you can do is create static event in another class and then get Form 1 to subscribe to the event. Then when button clicked in Form 2 then raise the event for Form 1 to pick up on.

You can have declare the event in Form 1 if you like.

public class Form1 : Form
{
    public static event EventHandler MyEvent;

    public Form1()
    {
        Form1.MyEvent += new EventHandler(MyEventMethod);
    }

    private void MyEventMethod(object sender, EventArgs e)
    {
        //do something here
    }

    public static void OnMyEvent(Form frm)
    {
        if (MyEvent != null)
            MyEvent(frm, new EventArgs());

    }
}

public class Form2 : Form
{
    private void SaveButton(object sender, EventArgs e)
    {
        Form1.OnMyEvent(this); 
    }
}
Malcolm
Hey, I tried your approach, but I am unable to do this ----- if(Form1.MyEvent != null) Form1.Myevent(this, new EventArgs());------I get a compile-time error
Rashmi Pandit
Sorry Rashmi. I have fixed it now, you need to raise the event from with in Form1 so you need a static OnMyEvent in Form1, Then Form2 calls the OnMyEvent. Try it now.
Malcolm
+2  A: 

You can get a list of all currently open forms in your application through the Application.OpenForms property. You can loop over that list to find Form1. Note though that (in theory) there can be more than one instance of Form1 (if your application can and has created more than one instance).

Sample:

foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(Form1))
    {
        ((Form1)form).Close();
    }
}

This code will call YourMethod on all open instances of Form1.

(edited the code sample to be 2.0-compatible)

Fredrik Mörk