如何从form2调用form1中的函数? [英] How to call a function in form1 from form2 ?

查看:553
本文介绍了如何从form2调用form1中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我在自学C#时遇到问题.这里是.
在Windows窗体应用程序上,我有2个froms(Form1和Form2).我显示了Form2打开一个Excel文件并读取一些数据,然后在Form2上单击确定"时,我需要在Form1上执行一个函数,并且可以关闭Form2(当然,我可以通过this.close()来做到这一点.) br/> 请让我知道如何从Form2调用Form1中的函数.
我需要这样做,因为form1包含需要处理的数据.

Hello,
I have a problem while i am self learning C#. Here it is.
On a windows form application i have 2 froms(Form1 and Form2) . I show the Form2 to open an Excel file and read some data and then upon clicking "ok" on Form2 i need to execute a function on form1 and form2 can be closed(Of course i do this by this.close()).
Kindly let me know how i can call functions in form1 from form2.
I need to do this because form1 has data which needs to be worked upon.

推荐答案

这是一个有关表单协作的流行问题.最健壮的方法是通过表单类实现适当的接口.

有关更多详细信息,请参见我过去的回答:
如何在列表框之间复制所有项目两种形式 [ ^ ].另请参阅其他建议和讨论.

—SA
This is a popular question about form collaboration. The most robust way is implementation of appropriate interface by the form class.

For more details, please see my past answer:
How to copy all the items between listboxes in two forms[^]. See also other suggestions and discussion.

—SA


您好,

您还可以使用委托:

在Form2中:

Hello,

You can also use delegate:

In Form2:

public delegate void methodHandler();
public methodHandler OnRunMethod;



在确定单击"事件中:



In OK Click event:

if (OnRunMethod != null)
    OnRunMethod();


例如:


example:

private void OK_Click(object sender, RoutedEventArgs e)
{
    if (OnRunMethod != null)
        OnRunMethod();
}



在Form1(打开Form2的位置)中:



In Form1 (where you open Form2):

Form2 form2 = new Form2();
form2.OnRunMethod += new methodHandler(MyMethod);
form2.Show() // or ShowDialog()



并在Form1中:



and in Form1:

private void MyMethod()
{
    //Do somethings
}



我认为这是一种完美的方法,因为可以从Form2调用它,并且可以同时使用Show()或ShowDialog().

祝你好运.



I think it''s a perfect way because it can be called from Form2 and you can use both of Show() or ShowDialog().

Good luck.


在打开Form2的Form1上,请遵循以下操作-

1.为表单创建对象
Form2 f = new Form2();
2.使用f.ShowDialog()打开表单
3.做您在form2中所做的事情
4.在f.ShowDialog()之后编写其他内容,将在关闭form2之后运行.
On Form1''s event where you open Form2, follow this -

1. Create object for form
Form2 f = new Form2();
2. Use f.ShowDialog() to open the form
3. Do what you do in form2
4. Code the other stuff after f.ShowDialog() which would run after form2 is closed.


这篇关于如何从form2调用form1中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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