Iterate child ToolStripMenuItem

G

Guest

I have a MenuStrip with a bunch of menus and sub-menus. On one of the
top-level menus I want all sub-items except the first to be disable/enabled
based on Checked setting of the first. Like so:

foreach (ToolStripMenuItem item in designToolStripMenuItem.Items)
if (item != topDesignToolStripMenuItem) item.Enabled = ...

Problem is that ToolStripMenuItem does not have an Items property. If you
iterate the ToolStripMenuItems in MenuStrip.Items you only get the top-level
items, none of their children.
How do i iterate the children?
 
J

Jeff Gaines

I have a MenuStrip with a bunch of menus and sub-menus. On one of the
top-level menus I want all sub-items except the first to be disable/enabled
based on Checked setting of the first. Like so:

foreach (ToolStripMenuItem item in designToolStripMenuItem.Items)
if (item != topDesignToolStripMenuItem) item.Enabled = ...

Problem is that ToolStripMenuItem does not have an Items property. If you
iterate the ToolStripMenuItems in MenuStrip.Items you only get the
top-level
items, none of their children.
How do i iterate the children?

A ToolStripMenuItem has DropDownItems. You need to find the top level item
then use HasDropDownItems to see if it has any items and if so iterate
through its DropDownItems. There are still some issues, if you iterate
through items cast as DropDownItems and one turns out to be a separator
then you will get an error message. I think I overcame this by using a
generic approach like foreach(object obTemp in topMenu.DropDownItems) then
using a try/catch block to cast it to a ToolStripMenuItem. I can't find my
code at the moment so I can't post an example.
 
G

Guest

Hi,
Private Sub SetAllMenuItems(ByRef menuStrip As MenuStrip, ByVal enable As
Boolean)
Dim c As ToolStripItem
Dim t As ToolStripMenuItem
For Each c In menuStrip.Items

c.Enabled = enable

If c.GetType Is GetType(ToolStripMenuItem) Then

t = c
SetAllMenuItems(t.DropDownItems, enable)

End If
Next
End Sub

Private Sub SetAllMenuItems(ByRef menus As ToolStripItemCollection, ByVal
enable As Boolean)

Dim c As ToolStripItem

Dim t As ToolStripMenuItem

For Each c In menus

c.Enabled = enable

If c.GetType Is GetType(ToolStripMenuItem) Then

t = c

SetAllMenuItems(t.DropDownItems, enable)

End If

Next

End Sub

Just call "SetAllMenuItems(Me.MenuStrip1, False)"
Hope this is what you needed.
ref:http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=564213&SiteID=1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top