How to call function from another form

后端 未结 4 2062
傲寒
傲寒 2020-12-17 01:46

In my project I have a Settings form and a Main form. I\'m trying to call the Main form\'s MasterReset function from the Setting form, but nothing happens.
The Master fo

4条回答
  •  萌比男神i
    2020-12-17 02:22

    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).

提交回复
热议问题