Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method from another form

Tags:

c#

winforms

I try to call a method from another form. My try:

public partial class newLedPopUp : Form
{
    Form1 back = new Form1();
    back.output();
    Close();
}

and

public partial class Form1 : Form
{
    newLedPopUp popup = new newLedPopUp();

    public void output()
    {
        button3_Click(null, null);
    }
}

Can somebody help me? I really can't find my error and I've been looking for a very long time.

like image 612
BudBrot Avatar asked Nov 28 '22 00:11

BudBrot


1 Answers

Instead of creating an instance of a new Form, you probably need an instance of already opened form and call the method from there. You can try:

if (System.Windows.Forms.Application.OpenForms["yourForm"] != null)
    {
        (System.Windows.Forms.Application.OpenForms["yourForm"] as Form1).Output();
    }

plus you can replace calling the button3_Click(null,null) in your Output method, by placing the code of the event in a separate method and then calling that method against your button click event or your public output method

like image 180
Habib Avatar answered Dec 18 '22 05:12

Habib