【问题标题】:Accessing methods on open form from a parent form c#从父表单c#访问打开表单上的方法
【发布时间】:2014-07-14 05:18:03
【问题描述】:

我想从父窗体访问子窗体中的方法。我已使用以下代码访问控件。

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

使用以下代码,我可以从父窗体访问子窗体中的控件。 我想以同样的方式访问子表单中的函数/方法。 例如:from.newmethod();

是否有可能实现这一点,而无需创建新的表单实例。使用 c#.net 的 Windows 应用程序

谢谢。

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    将方法声明为 public 不是一个好习惯。您可以改为创建委托或事件。您可以为该方法创建公共委托并从类外部执行该委托或者您可以创建可以从类外部处理的事件。

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

    现在,您可以从类外部调用此委托

    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.
        }
    }
    

    【讨论】:

    • 我没有得到这个 frm.delmyfunction。
    • 我无法在父表单中访问此委托,我已在子表单中声明了该委托
    • 声明delegate 时出错。将public delegate sub delegateName();这一行更改为public delegate void delegateName();
    猜你喜欢
    • 2012-10-26
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2011-06-30
    • 2012-04-28
    • 2014-09-05
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多