How to open the second form?
//To open the form
Form2 form2 = new Form2();
form2.Show();
// And to close
form2.Close();
Hope this helps
If you want to open Form2
modally (meaning you can't click on Form1 while Form2 is open), you can do this:
using (Form2 f2 = new Form2())
{
f2.ShowDialog(this);
}
If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:
private Form2 _f2;
public void openForm2()
{
_f2 = new Form2();
_f2.Show(this); // the "this" is important, as this will keep Form2 open above
// Form1.
}
public void closeForm2()
{
_f2.Close();
_f2.Dispose();
}
You need to handle an event on Form1 that is raised as a result of user interaction. For example, if you have a "Settings" button that the user clicks in order to show the settings form (Form2), you should handle the Click
event for that button:
private void settingsButton_Click(Object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
}
In addition to the Show
method, you could also choose to use the ShowDialog
method. The difference is that the latter shows the form as a modal dialog, meaning that the user cannot interact with the other forms in your application until they close the modal form. This is the same way that a message box works. The ShowDialog
method also returns a value indicating how the form was closed.
When the user closes the settings form (by clicking the "X" in the title bar, for example), Windows will automatically take care of closing it.
If you want to close it yourself before the user asks to close it, you can call the form's Close
method:
this.Close();