-4
private void toolStripButton7_Click(object sender, EventArgs e)
{
    if(panel1.Visible = false)
    {
        panel1.Visible = true;
    }
    if (panel1.Visible = true)
    {
        panel1.Visible=false;
    }
}

I have that code, and its suposed to change the visible property of a panel in WinForms, but it only works one time, and then, it never works again until I restart my program.

I first tried to add an else instead of two separate ifs, but that didn't solve my problem, and the panel is just not showing up after making it invisible.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • Is this your complete code? With property assignments in your conditions? Equity comparison is `==`, suggest you change your if statement to compare the value. – Adrian Mar 08 '23 at 18:47
  • Please post your actual code. This will never work. – Fildor Mar 08 '23 at 18:51
  • @Fildor It will work, it just won't produce the correct/desired output. – Adrian Mar 08 '23 at 18:51
  • 1
    Depends on your definition of "work" :D – Fildor Mar 08 '23 at 18:52
  • 1
    @Fildor Lol, while true now I wonder if you just came here to state the obvious back to OP :D – Adrian Mar 08 '23 at 18:53
  • The reason it doesn't work is because you are making an assignment (one equals sign vs. two equals signs) within the if statement boolean check. In this snippet, `if(panel1.Visible = false)`, you are setting the visibility of panel1 to false. [When you make an assignment, the value being assigned is actually "returned" as well](https://stackoverflow.com/questions/3807192/why-do-assignment-statements-return-a-value), so an equivalent statement would be `if (false)` which of course never runs. The same is true of the other if statement except you are setting it to true making it run every time. – Idle_Mind Mar 08 '23 at 20:10

1 Answers1

1

Why not literally toggle the visibility state?

private void toolStripButton7_Click(object sender, EventArgs e)
{
   panel1.Visible = !panel1.Visible;
}

"Fixing" your original code...inside the if statement expression, there should be TWO equals signs so that you are checking for equality. You're currently making an assignment in there. You don't need the second if check, either, just use an else block.

private void toolStripButton7_Click(object sender, EventArgs e)
{
   if (panel1.Visible == false)
    {
        panel1.Visible = true;
    }
    else
    {
        panel1.Visible = false;
    }
}
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40