从消息框中关闭所需的表单! (c#)
我的表单如下 - Form1 是第一个表单。我使用 showdialog
方法从 Form1 移动到 Form2(Form1 在后台,Form2 在顶部)。现在,单击 Form2 上的按钮时,会显示一个消息框
(请注意,Form1 仍然在后台)。 Messagebox
只有“确定”按钮。现在,当我按 OK
时,我想要加载 Form3 并想要关闭 Form2 和 Form1。如何关闭Form2和Form1?我在Form2中使用了这段代码:
private void button1_Click(object sender, EventArgs e)
{
if (...)
{
MessageBox.Show("hello");
this.DialogResult = DialogResult.OK;
this.Close();
Form3 frm = new Form3();
frm.ShowDialog();
}
}
此方法不会关闭Form2和Form1,但会显示Form3。所以我在 Form2 中尝试了这个:
private void button1_Click(object sender, EventArgs e)
{
if (...)
{
if (MessageBox.Show("hello") == DialogResult.OK)
{
this.Close();
Form3 frm = new Form3();
frm.ShowDialog();
}
}
}
仍然两个表单都没有关闭。我尝试在 MessageBox.Show
下的 Form2 中调用在 Form1 和 Form2 中创建的公共关闭方法(Form1 和 Form2 中的 this.Close
)。仍然没有任何效果。如何使用消息框的“确定”按钮摆脱这两种形式?
谢谢。简单但棘手..请留下代码片段。不幸的是我不懂技术术语:-(
Here's how my forms are - Form1 is the first form. From Form1 I move to Form2 by using showdialog
method (Form1 is in the background and Form2 on top). Now on clicking a button on Form2, a messagebox
is shown (mind you, Form1 is still in the background). Messagebox
has just the OK button. Now, when I press OK
I want to load Form3 and want to close both Form2 and Form1. How can I close Form2 and Form1?? I used this code in Form2:
private void button1_Click(object sender, EventArgs e)
{
if (...)
{
MessageBox.Show("hello");
this.DialogResult = DialogResult.OK;
this.Close();
Form3 frm = new Form3();
frm.ShowDialog();
}
}
This method doesn't close Form2 and Form1 but Form3 is showed. So I tried this in Form2:
private void button1_Click(object sender, EventArgs e)
{
if (...)
{
if (MessageBox.Show("hello") == DialogResult.OK)
{
this.Close();
Form3 frm = new Form3();
frm.ShowDialog();
}
}
}
Still both the forms aren't closed. I tried calling a public close method (this.Close
in Form1 and Form2) created in Form1 and Form2 from Form2 under the MessageBox.Show
. Still nothing worked. How to get rid of both forms with message box's OK button??
Thanks. Simple but tricky.. Kindly leave code snippet. I dont understand technical terms unfortunately :-(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要知道要关闭的实例(在本例中为表单)。
在 Form2 中,您可以创建一个变量(例如
theOneForm
)来存储对 Form1 的引用,并在创建 Form1 后(甚至在 Form1 的构造函数中)对其进行设置。然后从
button1_Click
调用theOneForm.Close()
- 这应该关闭您的 Form1。另外,执行其他代码后关闭表单。
You need to know the instances (forms in this case) that you want to close.
In Form2, you could create a variable (e.g.
theOneForm
) to store a reference to Form1 in and set it after creating Form1 (or even in the constructor of Form1).Then from your
button1_Click
, calltheOneForm.Close()
- this should close your Form1.Also, close your form after you executed the other code.