Mahsa
Mahsa

Reputation: 507

How to set a ToolStripMenuItem Visible in code?

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?

Upvotes: 1

Views: 6168

Answers (1)

Jcl
Jcl

Reputation: 28272

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.

Upvotes: 4

Related Questions