There is a common and simple requirement in windows applications to Open a new form(say Form2) when clicked a button in Form1 and also close Form1 at the same time.
Table of Contents
On Button Click Open Form 2 and Close Form 1
There are many ways you can close current form and open a new form in .NET.See below,
1) Close Form1 and Show Form2 – C#
private void btnLogin_Click(object sender, EventArgs e)
{
this.Close(); //Close Form1,the current open form.
Form2 frm2 = new Form2();
frm2.Show(); // Launch Form2,the new form.
}
2) Use Application.Run for each form in Main() method
//Declare a boolean property.This property to be set as true on button click.
public bool IsLoggedIn { get; set; }
private void btnLogin_Click(object sender, EventArgs e)
{
this.Close(); //Close Form1
/* Set the property to true while closing Form1.This propert will be checked
before running Form2 in Main method.*/
IsLoggedIN = true;
}
Then Update the Main() method as below.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 frm1 = new Form1();
Application.Run(frm1);
/*Here the property IsLoggedIn is used to ensure that Form2 won't be shown when user closes Form1 using X button or a Cancel button inside Form1.*/
if (frm1.IsLoggedIn)
{
Application.Run(new Form2());
}
}
3) Hide Form1 and Show Form2 – C#
Here Form1 will remain open as long as the application is live.This option is the worst and hence not at all suggested.
private void btnLogin_Click(object sender, EventArgs e)
{
this.Hide(); //Hide Form1.
Form2 frm2 = new Form2();
frm2.Show(); // Launch Form2
}
Summary
In this post we have seen samples to close Form1 and open Form2 in C# and same code logic can be used in VB.NET. Hope these code snippets has helped you to rectify the issues during close one form and open another form in C# or VB.NET. Leave your comments in the comment section below.
Related Items :
Close one form and Open another form On Button click,
Open new Form but Closing current Form,
vb.net close form from another form,
How to close form1 and open form2 in VB.NET,
Application.run to close a form and open another form
Sathira says
Thank you !!! This helped me a lot !!!