2

Well i've tried this:

private IEnumerable<ToolStripMenuItem> GetItems(ToolStripMenuItem item)
{
    foreach (ToolStripMenuItem dropDownItem in item.DropDownItems)
    {
        if (dropDownItem.HasDropDownItems)
        {
            foreach (ToolStripMenuItem subItem in GetItems(dropDownItem))
                yield return subItem;
        }
        yield return dropDownItem;
    }
}

private void button2_Click_1(object sender, EventArgs e)
{
    List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
    foreach (ToolStripMenuItem toolItem in menuStrip1.Items)
    {
        allItems.Add(toolItem);
        MessageBox.Show(toolItem.Text);
        allItems.AddRange(GetItems(toolItem));
    }
}

but i only get File, Edit, View

enter image description here

i need to reach Export (see the figure) and its subitem, and maybe change the visibility of Word for example.

NOTE: the form changes the menustrip item dynamically thats why i need to loop through them.

Community
  • 1
  • 1
Maged E William
  • 436
  • 2
  • 9
  • 27

2 Answers2

5

based on the details you provided you can use linq as

var exportMenu=allItems.FirstOrDefault(t=>t.Text=="Export");
if(exportMenu!=null)
{
    foreach(ToolStripItem item in exportMenu.DropDownItems) // here i changed the var item to ToolStripItem
    {
         if(item.Text=="Word") // as you mentioned in the requirements
              item.Visible=false; // or any variable that will set the visibility of the item
    }
}

hope that this will help you

regards

Monah
  • 6,714
  • 6
  • 22
  • 52
  • well, i can't test it, there's blue line under `item.Text` and `item.Visible` "object does not contain a definition for text, Visible...." – Maged E William Feb 25 '14 at 13:23
  • 1
    this because the compiler didn't know what is the type of item in the foreach loop, instead of (var item) put (ToolStripItem item) and give it a try – Monah Feb 25 '14 at 13:37
0

In order to get all the menu items (ToolStripMenuItem instances) in your MenuStrip use the following code (I assume the MenuStrip name is menuStrip1)

// Get all the top menu items, e.g. File , Edit and View
List<ToolStripMenuItem> allItems = new List<ToolStripMenuItem>();
foreach (ToolStripMenuItem item in menuStrip1.Items)
{
   // For each of the top menu items, get all sub items recursively
    allItems.AddRange(GetItems(item)); 
}
sh_kamalh
  • 3,853
  • 4
  • 38
  • 50