Calling a method in form 1 by pressing a button on form2

I am completely new to windows forms. I would like to know if it is possible to run a method in form 1 when you click a button in form 2? My form 1 has a summary. My form 2 has a Save button. I would like to achieve: When the user clicks the "Save" button in form 2, I need to check if form 1 is open. If it is open, I want to get an instance and call a method that will overflow the combo in form 1.

I would really appreciate it if I received some guidance on how I can do this. If there is another better way than this, please 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.

+3
source share
3 answers

You can get a list of all currently open forms in your application through the Application.OpenForms property . You can iterate over this list to find Form1. Please note that (theoretically) there can be more than one instance of Form1 (if your application can and has created several instances).

Example:

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

This code will call YourMethodin all open instances of Form1.

(edited sample code compatible with 2.0)

+2
source

Of course, this is possible, all you need is a link to Form1 and a public method in this class.

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

0

What you can do is create a static event in another class and then get form 1 to subscribe to the event. Then, when the button is pressed in Form 2, raise the event for Form 1 to select.

You can declare an event in Form 1 if you wish.

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); 
    }
}
0
source

Source: https://habr.com/ru/post/1709286/


All Articles