1

I have some code in Windows Forms application.
I want to change the visibility of my drop down ToolStripMenuItems in code.
I set the Visible property, but when I set a breakpoint and inspect the property value, the visibility of the items has not changed.

Here is my code:

foreach (ToolStripMenuItem it in _frmMain.menuStripMain.Items)
{
   foreach (ToolStripMenuItem i in it.DropDownItems)
   {
       if (i.Text == this._listAppSchema[0].ObjectName.ToString())
       {
          i.Visible = true;
       }
       else
       {
          i.Visible = false;
       }                                                
   }                                           
}

How to Solve this?

Jimi
  • 29,621
  • 8
  • 43
  • 61
Mahsa
  • 477
  • 1
  • 5
  • 9
  • I just tested this and it works fine from a hover event on one of the drop down items. So it must be as @Jcl says and you have something more complex going on not captured in your snippet. – zeromus Jul 04 '16 at 05:23
  • Yes... apart from that (I added it to my answer), you should not use `Visible` for `ToolStriptem`s... there's an `Available` property for showing/hiding entries in a menu. – Jcl Jul 04 '16 at 05:25

1 Answers1

4

Visible is a complicated property. It doesn't set and read the same.

If you set it to true or false it says whether the object will be (or not) visible. However when you read it, it shows whether that control's visibility is set to true or false, but it will read as false if any parent in the chain is also hidden.

So setting and reading it is a different thing: even if you set it to true, it may come false in the debugger when you read it back (again, if any parent in the chain is hidden): it'll become true when all the parents are visible though.

For ToolStripItem specifically though, use the Available property instead of Visible: this should do what you are expecting. The documentation (which I linked) talks specifically about this:

The Available property is different from the Visible property in that Available indicates whether the ToolStripItem is shown, while Visible indicates whether the ToolStripItem and its parent are shown. Setting either Available or Visible to true or false sets the other property to true or false.

Jcl
  • 27,696
  • 5
  • 61
  • 92