Search code examples
c#winformsmdiparent

Use function from another form


UPDATED

MDIparent Form:

public void sample()
{
textBox1.Text = "Sample";
}

private void button1_Click(object sender, EventArgs e)
{
MDIParent1 p = new MDIParent1();
LogInForm LogIn = new LogInForm(p); 
DialogResult res = LogIn.ShowDialog()
}

LogInForm:

private MDIParent1 _p;
public LogInForm(MDIParent1 p)
{
InitializeComponent();
_p = p;
}

private void button1_Click(object sender, EventArgs e)
{
_p.sample();
this.Close();
}

_p.sample(); does not work


Solution

  • public void sample()
    {
       textBox1.Text = "Sample";
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
       MDIParent1 p = new MDIParent1();
       LogInForm LogIn = new LogInForm(p); 
       DialogResult res = LogIn.ShowDialog()
    }
    

    On button click here, you are creating a NEW MDIParent1 and passing that to the new LogInFOrm

    private MDIParent1 _p;
    public LogInForm(MDIParent1 p)
    {
       InitializeComponent();
       _p = p;
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
       _p.sample();
    }
    

    Here you call the sample method on the form you passed in (which has been instanitated on the previous form, but never actually rendered).To render it you need to call Show() or ShowDialog()

    If you were meaning to pass in the form where the button was clicked you could have done this

    LogInForm LogIn = new LogInForm(this);
    

    or you could have used Application.OpenForms and not passed the form at all.