Reputation: 111
I have three forms in my application.
Form1 is the main form. Form2 is a form with two input fields. Form3 is a password verification form which is triggered from Form1 and upon successful authentication, Form2 is shown.
Form1 -> Form3 -> Form2
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.textBox_entry_password.Text))
{
MessageBox.Show("Please enter a password", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
this.textBox_entry_password.Focus();
}
else
{
// Authentication not Implemented so far
Form Form2 = new Form2();
Form2.StartPosition = FormStartPosition.CenterScreen;
// Code for hiding Form3 -- Needed ????
Form2.ShowDialog();
}
I want Form1 to stay as such and hide Form3 and show Form2.
this.hide()
hides Form1.
If i try
Form Form3 = new Form3();
Form3.Hide();
It does nothing. Form3 stays right there.
How do i hide Form3?
Upvotes: 1
Views: 152
Reputation: 1135
Ther are many ways to do this. Below is an approach that I like because the password form is only concerned with obtaining and authenticating a password, and knows nothing about Form1 and Form2.
Code in Form3:
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.textBox_entry_password.Text))
{
MessageBox.Show("Please enter a password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
this.textBox_entry_password.Focus();
}
else
{
// Authentication code here
// if (isAuthenticated)
// {
// DialogResult = DialogResult.OK;
// Close(); // hides and closes the form
// }
}
}
Code in Form1, to use Form 3 and Form2:
var dialogResult = DialogResult.Cancel;
// Always explicitly dispose a form shown modally; using clause will do this.
using (var form3 = new Form3())
{
dialogResult = form3.ShowDialog(this);
}
if (dialogResult == DialogResult.OK) // password authenticated
{
// Always explicitly dispose a form shown modally; using clause will do this.
using (var form2 = new Form2())
{
dialogResult = form2.ShowDialog(this);
}
}
Upvotes: 0
Reputation:
Create an overload of your Form3()
constructor and pass Form1
instance to it.
private Form form;
public Form3(Form frm)
{
form = frm;
}
Now wherever you want to hide/show form1, just use form.Hide(), form.Show();
In your case use
if (string.IsNullOrEmpty(this.textBox_entry_password.Text))
{
MessageBox.Show("Please enter a password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
this.textBox_entry_password.Focus();
}
else
{
// Authentication not Implemented so far
Form Form2 = new Form2();
Form2.StartPosition = FormStartPosition.CenterScreen;
// Code for hiding Form3 -- Needed ????
Form2.ShowDialog();
this.Hide();
form.ShowDialog();
}
Upvotes: 0
Reputation: 9081
try this :
Form2 a = new Form2 ();
a.Show();
this.Close();
in the button click event inside Form3
Upvotes: 1