How to call function from another form

后端 未结 4 2069
傲寒
傲寒 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-17 02:33

    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!

提交回复
热议问题