C# 从另一个表单调用方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12890754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:51:05  来源:igfitidea点击:

Call a method from another form

c#winforms

提问by BudBrot

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.

有人可以帮助我吗?我真的找不到我的错误,我已经找了很长时间了。

采纳答案by Habib

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 Outputmethod, 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

此外,您可以通过将事件代码放在单独的方法中,然后针对按钮单击事件或公共输出方法调用该方法来替换button3_Click(null,null)在您的Output方法中调用

回答by Sergey Berezovskiy

You are closing Form1immediately after calling outputmethod. Thus I assume, you have some business-related, or data access logic there. Try to move code, which is executed on button3_Clickevent handler, to separate object

Form1在调用output方法后立即关闭。因此,我假设您在那里有一些与业务相关的或数据访问逻辑。尝试将在button3_Click事件处理程序上执行的代码移动到单独的对象

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 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();
     }
}