Firing a method in form 1 on click of a button on form2

空扰寡人 提交于 2019-12-04 15:47:49

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)

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.

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); 
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!