访问开放的形式方法从父窗体C#窗体、形式、方法

2023-09-05 03:24:03 作者:清欢

我想从父form.I访问子窗体的方法使用了下列code访问控制。

I want to access a method in a child form from parent form.I have used the following code to access the controls.

Form form = (Form)Application.OpenForms["frmname"];
if (tableform != null)
{
    GroupBox grp = (GroupBox)tableform.Controls["grpbxname"];
    Panel table = (Panel)grp.Controls["panelname"];
}

使用下面的code我能够从父窗体访问子窗体控件。 同样的方式,我想访问函数/方法的子窗体。 对于前:from.newmethod();

Using the following code I am able to access controls in the child form from the parent form. Same way I want to access the function/method in the child form. For ex: from.newmethod();

是否有可能实现这一目标,而无需创建的form.It Windows应用程序的新实例,使用C#.NET

Is there any possibility to achieve this,without creating new instance of form.It windows application using c#.net

感谢。

推荐答案

声明一个方法public是不是一个好的做法。您可以创建委托或事件来代替。您可以创建公共委托该方法,并从执行该委托类外还可以创建事件,你可以处理从类的外部。

declaring a method public is not a good practice. you can create delegate or event instead. you can create public delegate for that method and execute that delegate from the outside the class Or you can create Event that you can handle from the outside of the class.

public partial class Form1 : Form
{
    public delegate void dMyFunction(string param);
    public dMyFunction delMyFunction;

    public Form1()
    {
        InitializeComponent();
        delMyFunction = new dMyFunction(this.MyFunction);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2();
        frm.Show();
    }
    private void MyFunction(string param)
    {
        this.Text = param;
    }
}

现在,你可以调用该委托从类的外部

Now, you can call this delegate from the outside the class

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        Form1 frm = (Form1)Application.OpenForms["Form1"];
        frm.delMyFunction.Invoke("Hello");
        //On Form load this method will be invoked and Form1 title will be changed.
    }
}