Search code examples
c#menustrip

Loop through subitems in menustrip


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.


Solution

  • 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