How to call function from another form

亡梦爱人 提交于 2019-11-29 07:58:16
Blue0500

This worked for me: In your Program class, declare a static instance of Main (The class, that is) called Form. Then, at the beginning of the Main method, use Form = new Main(); So now, when starting your app, use Application.Run(Form);

public static Main Form;

static void Main() {
    Form = new Main();
    Application.Run(Form)
}

Now, calling a function from another form is simple.

Program.Form.MasterReset();  //Make sure MasterReset is a public void
BRAHIM Kamel

Do you know what composition over inheritance is?

In the form where you have MasterReset you should do something like this:

Llet's suppose that in your second form you have something like this, and let's suppose your "mainform" will be called "MasterForm".

public partial class Form1 : Form
{
    private MasterForm _masterForm;  

    public Form1(MasterForm masterForm )
    {
        InitializeComponent();
        _masterForm = masterForm;  

    }
}

Here's the code in your masterForm Class:

 private void button2_Click(object sender, EventArgs e)
 {
     Form1  form1 = new Form1(this);

 } 

Here's in your form1:

private void btn_MasterReset_Click(object sender, EventArgs e)
{
    _masterForm.MasterReset();
} 

Hope this helps!

There are multiple solutions possible. But the problem itself arise from the bad design. If you need something to be accessed by many, then why should it belong to someone? If, however, you want to inform something about anything, then use events.

Your mistake is what you are creating another instance of form1, thus MasterReset is operating with form, which is not even shown.

What you can do:

  1. Make (as Ravshanjon suggest) a separate class to handle that MasterReset (and maybe something else). But also add to it an event. form1 and form2 can both subscribe to it and whenever either of them call MasterReset - both will react.

  2. Create form dependency (as BRAHIM Kamel suggested): when you create form2, then pass to it form1 instance (as constructor parameter or by setting public property), to be able to call public non-static methods of form1.

  3. As a quick, but relatively legimate solution, make this method static:


private static Form1 _instance;

public Form1()
{
    InitializeComponents();
    _instance = this;
}

public static void MasterReset()
{
    // alot of code
    _instance.listView1.Clear();
    // alot of code
}

this way you can call MasterReset from any other form like this Form1.MasterReset(). Disadvantage of this method is what you can not have more than one instance of form2 (which is more likely anyway).

I understand your problem, you can declare your function as public static void(also listView1 and people should be static too). Then when you want to call to like this:

private void btn_MasterReset_Click(object sender, EventArgs e)
{
    Main.MasterReset();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!