访问开放的形式方法从父窗体C# [英] Accessing methods on open form from a parent form c#

查看:160
本文介绍了访问开放的形式方法从父窗体C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从父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.
    }
}

这篇关于访问开放的形式方法从父窗体C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆