user2234123
user2234123

Reputation:

What's up with this C# code?

I have a split container which I need to be able to show and hide.

I tried "wiring" the split container to a button using the following code:

if (toolStripButton2.Checked == false)
{
    toolStripButton2.Checked = true;
    this.WindowState = FormWindowState.Maximized;
    splitContainer1.Panel2Collapsed = false;
    splitContainer1.Panel2.Show();                
}
if (toolStripButton2.Checked == true)
{
    toolStripButton2.Checked = false;
    splitContainer1.Panel2Collapsed = true;
    splitContainer1.Panel2.Hide();          
}

But it doesn't seem to work. I can't see any issue with the code. Maybe I'm overlooking something?

Any ideas?

--EDIT--

In order to get the contents of panel2 to display correctly, I need to maximize the form.

Upvotes: 0

Views: 226

Answers (3)

w5l
w5l

Reputation: 5776

Where are you running this code? You probably want to catch the CheckChanged event on the button. Wire up a handler in your form OnLoad:

toolStripButton2.CheckChanged += toolStripButton2_CheckChanged;

And place the following handler, which will be executed after the check is changed:

public void toolStripButton2_CheckChanged(object sender, EventArgs e)
{
    if (toolStripButton2.Checked)
    {
        splitContainer1.Panel2Collapsed = true;
        splitContainer1.Panel2.Hide();

    }
    else
    {
        splitContainer1.Panel2Collapsed = false;
        splitContainer1.Panel2.Show();
    }
}

Since this handler runs after check is changed, you don't need to manually set the check state! If you set the check state to false when it is true (or the other way around), you would effectively UNDO the change.

Upvotes: 5

Tanner
Tanner

Reputation: 22753

Shouldn't it be:

if (toolStripButton2.Checked == false)
{
        toolStripButton2.Checked = true;
        this.WindowState = FormWindowState.Maximized;
        splitContainer1.Panel2Collapsed = false;
        splitContainer1.Panel2.Show();

}
else //toolStripButton2.Checked == true
{
        toolStripButton2.Checked = false;
        splitContainer1.Panel2Collapsed = true;
        splitContainer1.Panel2.Hide();
}

Upvotes: 2

Martin
Martin

Reputation: 16453

It looks like you have a logical error in your code. If the Checked state is False, you then set it to True, which means your second if statement will be true, and the code will run in it.

Try using an else statement instead:

if (toolStripButton2.Checked == false)
{
    toolStripButton2.Checked = true;
    this.WindowState = FormWindowState.Maximized;
    splitContainer1.Panel2Collapsed = false;
    splitContainer1.Panel2.Show();
}
else 
{
    toolStripButton2.Checked = false;
    splitContainer1.Panel2Collapsed = true;
    splitContainer1.Panel2.Hide();
}

Upvotes: 8

Related Questions