Reputation: 119
Now, I have two forms, called form1 and form2, in the form1 there's a button, when I click it, then open the form2
Question: in the form2, I want to create a button when I click it, the form2 close and the form1 close. How to do?this
Upvotes: 4
Views: 125243
Reputation: 1
private void button1_Click(object sender, EventArgs e)
{
Form2 m = new Form2();
m.Show();
this.Visible = false;
}
Upvotes: 0
Reputation: 1
//program to form1 to form2
private void button1_Click(object sender, EventArgs e)
{
//MessageBox.Show("Welcome Admin");
Form2 frm = new Form2();
frm.Show();
this.Hide();
}
Upvotes: 0
Reputation: 11
This works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Hide()
Form2.Show()
Upvotes: 1
Reputation: 3738
I did this once for my project, to close one application and open another application.
System.Threading.Thread newThread;
Form1 frmNewForm = new Form1;
newThread = new System.Threading.Thread(new System.Threading.ThreadStart(frmNewFormThread));
this.Close();
newThread.SetApartmentState(System.Threading.ApartmentState.STA);
newThread.Start();
And add the following Method. Your newThread.Start will call this method.
public void frmNewFormThread)()
{
Application.Run(frmNewForm);
}
Upvotes: 0
Reputation: 1456
if you just want to close form1 from form2 without closing form2 as well in the process, as the title suggests, then you could pass a reference to form 1 along to form 2 when you create it and use that to close form 1
for example you could add a
public class Form2 : Form
{
Form2(Form1 parentForm):base()
{
this.parentForm = parentForm;
}
Form1 parentForm;
.....
}
field and constructor to Form2
if you want to first close form2 and then form1 as the text of the question suggests, I'd go with Justins answer of returning an appropriate result to form1 on upon closing form2
Upvotes: 0
Reputation: 11644
on the form2.buttonclick put
this.close();
form1 should have object of form2.
you need to subscribe Closing event of form2.
and in closing method put
this.close();
Upvotes: 0
Reputation: 3754
Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.Show();
}
Form2:
public partial class Form2 : Form
{
Form opener;
public Form2(Form parentForm)
{
InitializeComponent();
opener = parentForm;
}
private void button1_Click(object sender, EventArgs e)
{
opener.Close();
this.Close();
}
}
Upvotes: 9
Reputation: 134167
Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.
Upvotes: 0