BudBrot
BudBrot

Reputation: 1411

Call a method from another form

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.

Upvotes: 6

Views: 41422

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

You are closing Form1 immediately after calling output method. Thus I assume, you have some business-related, or data access logic there. Try to move code, which is executed on button3_Click event handler, to separate object

public class Foo
{
    public void Output()
    {
       // move here button3_Click code
    }
}

Then create Foo and pass it to both forms (or you can instantiate it inside forms without dependency injection)

Foo foo = new Foo();
Form1 form1 = new Form1(foo);
LedPopUp form2 = new LedPopUp(foo);

And use it like this:

public partial class Form1 : Form
{
     private Foo _foo;
     // without dependency injection: private Foo _foo = new Foo();         

     public Form1(Foo foo)
     {
         _foo = foo;
     }

     protected void button3_Click(object sender, EventArgs e)
     {
         _foo.Output();
     }
}

Upvotes: 2

Habib
Habib

Reputation: 223187

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

Upvotes: 38

Related Questions