【发布时间】:2014-02-28 17:22:00
【问题描述】:
如何从另一个窗体关闭事件中调用窗体的方法? 假设 second for 正在关闭,我想在 second 关闭时调用第一个窗体的方法以更新第一个窗口窗体上的一些更改。
【问题讨论】:
-
你尝试了吗?您用
Show或ShowDialog方法打开第二个表单?
标签: c# .net winforms c#-4.0 window
如何从另一个窗体关闭事件中调用窗体的方法? 假设 second for 正在关闭,我想在 second 关闭时调用第一个窗体的方法以更新第一个窗口窗体上的一些更改。
【问题讨论】:
Show 或ShowDialog 方法打开第二个表单?
标签: c# .net winforms c#-4.0 window
您可以在第一个表单中为form_closing 事件添加事件处理程序并进行相应处理。
form1某处
form2.Form_Closing += yourhandler;
【讨论】:
这里假设表单 2 有一个名为 TextBox1 的控件,当表单 2 关闭时,将调用 lambda 表达式并将数据传输到表单 1。
public partial class Form1 : Form
{
private Form2 openedForm2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Not sure if you would want more than 1 form2 open at a time.
if (this.openedForm2 == null)
{
this.openedForm2 = new Form2();
//Here is your Event handler which accepts a Lambda Expression, code inside is performed when the form2 is closed.
this.openedForm2.FormClosing += (o, form) =>
{
// this is Executed when form2 closes.
// Gets text from Textbox1 on form2 and assigns its value to textbox1 on form 1
this.textBox1.Text = ((Form2)o).Controls["TextBox1"].Text;
// Set it null so you can open a new form2 if wanted.
this.openedForm2 = null;
};
this.openedForm2.Show();
}
else
{
// Tells user form2 is already open and focus's it for them.
MessageBox.Show("Form 2 is already open");
this.openedForm2.Focus();
}
}
}
【讨论】:
将第一个表单中的引用传递给第二个表单。假设您以这种方式创建第二个表单(从您的第一个表单开始):
Form2 frm2 = new Form2();
frm2.referenceToFirstForm = this
在你的第二种形式中,你应该有这个:
public Form1 referenceToFirstForm
然后在您的OnClosing 事件中您可以引用referenceToFirstForm
【讨论】: