You have answered your own question. If you look at the code, not all panel visibility states are managed for each button. eg: button6 code does not change the panel1 visibility state, and so on...
You can either use the
State Design Pattern[
^] or a shared method and switch statement. But for something simple like above, you could do the following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SetState(States.first);
}
private void button1_Click(object sender, EventArgs e)
{
SetState(States.first);
}
private void button2_Click(object sender, EventArgs e)
{
SetState(States.second);
}
private void button3_Click(object sender, EventArgs e)
{
SetState(States.third);
}
private void button4_Click(object sender, EventArgs e)
{
SetState(States.forth);
}
private void button5_Click(object sender, EventArgs e)
{
SetState(States.fifth);
}
private void button6_Click(object sender, EventArgs e)
{
SetState(States.sixth);
}
private void button7_Click(object sender, EventArgs e)
{
SetState(States.seventh);
}
private void button8_Click(object sender, EventArgs e)
{
SetState(States.eighth);
}
private void button9_Click(object sender, EventArgs e)
{
SetState(States.nineth);
}
private void SetState(States state)
{
panel1.Visible = state == States.first;
panel2.Visible = state == States.second;
panel3.Visible = state == States.third;
panel4.Visible = state == States.forth;
panel5.Visible = state == States.fifth;
panel6.Visible = state == States.sixth;
panel7.Visible = state == States.seventh;
panel8.Visible = state == States.eighth;
panel9.Visible = state == States.nineth;
}
}
enum States
{
first,
second,
third,
forth,
fifth,
sixth,
seventh,
eighth,
nineth
}
** UPDATE: If you need to have more than one panel shown on a button click, you could use enum bitwise operation with the
Flags
attribute. Eg:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SetState(States.None);
}
private void button1_Click(object sender, EventArgs e)
{
SetState(States.first | States.third);
}
private void button2_Click(object sender, EventArgs e)
{
SetState(States.second);
}
private void button3_Click(object sender, EventArgs e)
{
SetState(States.third | States.second);
}
private void SetState(States state)
{
panel1.Visible = (state & States.first) != 0;
panel2.Visible = (state & States.second) != 0;
panel3.Visible = (state & States.third) != 0;
}
}
[Flags]
internal enum States
{
None = 0,
first = 1,
second = 2,
third = 4,
forth = 8,
fifth = 16,
sixth = 32,
seventh = 64,
eighth = 128,
nineth = 256
}