How to find toolstripmenuItem with name

2019-07-19 00:52发布

I have set visible property of my menuStrip1 items to false as

foreach (ToolStripMenuItem itm in menuStrip1.Items)
{
    itm.Visible = false;
}

Now I know the Names of toolStripMenuItem and dropDownItem of the menustrip1. How to can I activate the required toolStripMenuItem and dropDownItem.

I have

string mnItm = "SalesToolStripMenuItem";
string ddItm = "invoiceToolStripMenuItem";

Now I want to set visible true to these two(toolStripMenuItem and dropDownItem) items. How can I do that? I know those names only.

6条回答
疯言疯语
2楼-- · 2019-07-19 01:16
    private void ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string MenuItemName = sender.ToString()
    }
查看更多
SAY GOODBYE
3楼-- · 2019-07-19 01:18

You should try something like this:

string strControlVal ="somecontrol"; //"SalesToolStripMenuItem" or "invoiceToolStripMenuItem" in your case
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
     if (strControlVal == item.Name)
     { 
        item.Visible = false;
     }
}

Initialize strControlVal string on your discretion where you need it.

查看更多
Bombasti
4楼-- · 2019-07-19 01:19

Simply use those names to get the actual item via MenuStrip.Items indexer:

ToolStripMenuItem menuItem = menuStrip1.Items[mnItm] as ToolStripMenuItem;
ToolStripDropDownMenu ddItem = menuStrip1.Items[ddItm] as ToolStripDropDownMenu;
查看更多
Fickle 薄情
5楼-- · 2019-07-19 01:21

You can use

menuStrip1.Items[mnItm].Visible = true;
menuStrip1.Items[ddItm].Visible = true;

or if you want to set Visible to multiple toolstrip items:

string [] visibleItems = new [] {"SalesToolStripMenuItem", "invoiceToolStripMenuItem"};
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
     if (visibleItems.Contains(item.Name))
     { 
        item.Visible = false;
     }
}

Hope it helps

查看更多
何必那么认真
6楼-- · 2019-07-19 01:21

You're looking for ToolStripItemCollection.Find method.

var items = menustrip.Items.Find("SalesToolStripMenuItem", true);
foreach(var item in items)
{
    item.Visible = false;
}

second parameter says whether or not to search the childrens.

查看更多
相关推荐>>
7楼-- · 2019-07-19 01:24

If i get your question you are trying to disable other than the above two mentioned toolstrip items. Since you know the name of the menu items a slight change in code can get you along

  foreach (ToolStripMenuItem itm in menuStrip1.Items)
    {
       if(itm.Text !="SalesToolStripMenuItem" || itm.Text !="invoiceToolStripMenuItem")
        {
         itm.Visible = false;
        }
    }
查看更多
登录 后发表回答