Maged E William
Maged E William

Reputation: 446

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.

Upvotes: 2

Views: 7876

Answers (2)

Monah
Monah

Reputation: 6794

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

Upvotes: 5

sh_kamalh
sh_kamalh

Reputation: 3901

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)); 
}

Upvotes: 0

Related Questions