问题
I try to show/hide panels in C#, but when I clicked on button1 I wanted to see panel1 but panel2 appeared. And when I cliked on button2, panel2 dissappeared. But when I cliked first on button2, panel2 didn't appear. I don't know what is wrong with my code but here it is:
public Form3()
{
InitializeComponent();
}
bool show1;
bool show2;
private void button1_Click(object sender, EventArgs e)
{
if(show1)
{
panel1.Visible = false;
show1 = false;
}
else
{
panel1.Visible = true;
show1 = true;
}
Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
if (!show2)
{
panel2.Visible = true;
show2 = true;
}
else
{
panel2.Visible = false;
show2 = false;
}
Application.DoEvents();
}
回答1:
Don't use flags, because your button behavior will be determined by the states of the flags.
Best is to code it the way you want. If you want each Button
to make the corresponding panel visible while other panel invisible:
private void button1_Click(object sender, EventArgs e)
{
panel1.Visible = true;
panel2.Visible = false;
//Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
panel2.Visible = true;
panel1.Visible = false;
//Application.DoEvents();
}
Or, if you want each button to control the visibility of each panel independently, do this:
private void button1_Click(object sender, EventArgs e)
{
panel1.Visible = !panel1.Visible;
//Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
panel2.Visible = !panel2.Visible;
//Application.DoEvents();
}
Lastly, the Application.DoEvents()
can be removed (credit to Thorsten Dittmar) as the control will immediately back to UI thread after the Click
method finishes anyway. Read his comment and the referred link.
回答2:
Don't use global variable like show1
and show2
You can do like this instead.
private void button1_Click(object sender, EventArgs e)
{
panel1.Visible = !panel1.Visible;
Application.DoEvents();
}
回答3:
No need to use variables and condition.
Just add panel1.Visible = false; or panel1.Visible = true;
on button click
回答4:
You may find the solution but I just want to recommend you to use SuspendLayout()
and ResumeLayout()
for performance improvement while changing control states
private void button1_Click(object sender, EventArgs e)
{
this.SuspendLayout();
panel1.Visible = true;
panel2.Visible = false;
this.ResumeLayout();
//Application.DoEvents();
}
private void button2_Click(object sender, EventArgs e)
{
this.SuspendLayout();
panel2.Visible = true;
panel1.Visible = false;
this.ResumeLayout();
//Application.DoEvents();
}
来源:https://stackoverflow.com/questions/35741177/hide-show-windows-forms-panel-in-c-sharp