Using a button / event to show a new form and hide the exisiting one in C#
I am trying to click on a button in a form, by doing so it will hide the existing form and show the new one, although I have had problems, and also problems with the forms being "generated" in different locations on the screen!
My code is as follows:
private 开发者_如何学Govoid button1_Click(object sender, EventArgs e)
{
(new Form3()).Show();
(new Form2()).Hide();
}
This code shows the new form ok, but form2 does not hide
You're creating a new instance of Form2 and hiding THAT one. I'm guessing you're looking for this:
private void button1_Click(object sender, EventArgs e)
{
(new Form3()).Show();
this.Hide();
}
If you want to hide some form you need to call the .Hide()
method on the proper instance of it. So for example when you create the form you could store it to some variable:
Form2 form2 = new Form2();
and later when you want to hide this form:
form2.Hide();
You are hiding a new form. What you should do is keep a reference to the form you have opened and then hide it:
private void button1_Click(object sender, EventArgs e)
{
form3.Show();
form2.Hide();
}
private Form2 form2 = new Form2();
private Form3 form3 = new Form3();
The code (new Form2()).Hide();
instantiates a new instance of Form2
. In order hide an existing form, you'll need a reference to it.
You can't create a new instance of Form2 and expect the existing Form2 to be hidden. Store the existing Form2 to an instance variable of your class and call Hide() on that instance.
If you're trying to hide an existing form, (new Form2()).Hide()
won't do it, since that will instantiate a new form from the class Form2.
Presuming Button1 is on the form you want to hide, you want:
private void button1_Click(object sender, EventArgs e)
{
(new Form3()).Show();
this.Hide();
}
If it's not on the same form, you'll need a reference to the form you want to hide:
private Form2 form2 = new Form2();
private Form3 form3 = new Form3();
form2.Show();
private void button1_Click(object sender, EventArgs e)
{
form2.Hide();
form3.Show();
}
@BFree's is a good answer. Just for grins here's some code with Form1 having two buttons which toggle the two other subforms Form2 and Form3, after the Form1_Load does the initial instantiation and Show().
Form2 f2 = null;
Form3 f3 = null;
private void Form1_Load(object sender, EventArgs e)
{
f2 = new Form2();
f2.Show();
f3 = new Form3();
f3.Show();
}
private void button1_Click(object sender, EventArgs e)
{
if (f2.Visible)
{
f2.Hide();
}
else
{
f2.Show();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (f3.Visible)
{
f3.Hide();
}
else
{
f3.Show();
}
}
精彩评论