问题
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.
回答1:
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.
回答2:
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;
回答3:
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
回答4:
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.
回答5:
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;
}
}
回答6:
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
string MenuItemName = sender.ToString()
}
来源:https://stackoverflow.com/questions/18974249/how-to-find-toolstripmenuitem-with-name