How to cast Control to a DropDownMenuItem?

  • Thread starter Thread starter Armin Zingler
  • Start date Start date
A

Armin Zingler

Dean Slindee said:
I need to interate thru the menu items under a
ToolStripDropDownButton. Some of them are ToolStripMenuItems and
some are ToolStripSeparators. I want to deal only with the
ToolStripMenuItems, so am using Control in order to interate thru
the collection. However, when I do that, I cannot cast Control to a
ToolStripMenuItem. I need to use the
.DropDownItems.Add(menuItem) in order to add new dynamic menu items.

Here is the code:
Public Shared Sub DynamicMenuStripItemBuilder(ByRef frm As Form, _
ByRef btn As
ToolStripDropDownButton, _
ByRef ds As DataSet,
_ ByVal UserID As
String) For Each ctl In btn.DropDownItems
If ctl.GetType() Is Type.GetType("ToolStripMenuItem")
Then Dim mni As ToolStripMenuItem
mni = CType(ctl, ToolStripMenuItem) (SYNTAX ERROR)
Dim menuItem As New
ToolStripMenuItem(dr.Item("URLName").ToString, Nothing, New
EventHandler(AddressOf DynamicMenuStripItemHandler))
ctl.DropDownItems.Add(menuItem)
(SYNTAX ERROR)
End If
Next


Which VB version? If not 2008, you should enable Option Strict.

The items in btn.DropDownItems are of type ToolStripItem, not of type
Control.
=> For Each ctl As ToolStripItem In btn.DropDownItems

To check the type, use "TypeOf":

If TypeOf ctl Is ToolStripMenuItem Then
Dim mni As ToolStripMenuItem = DirectCast(ctl, ToolStripMenuItem)
Dim menuItem As New ToolStripMenuItem(...)
mni.DropDownItems.Add(menuItem)
End If


VB 2008+Option Infer On:

Dim mni = TryCast(ctl, ToolStripMenuItem)
If mni IsNot Nothing Then
Dim menuItem As New ToolStripMenuItem(...)
mni.DropDownItems.Add(menuItem)
End If


BTW, change ByRef to ByVal with 'frm' and 'btn' unless you want to assign a
new Form or ToolStripDropDownButton to these arguments.


Armin
 
I need to interate thru the menu items under a ToolStripDropDownButton.
Some of them are ToolStripMenuItems and some are ToolStripSeparators. I
want to deal only with the ToolStripMenuItems, so am using Control in order
to interate thru the collection. However, when I do that, I cannot cast
Control to a ToolStripMenuItem. I need to use the
..DropDownItems.Add(menuItem) in order to add new dynamic menu items.

Here is the code:
Public Shared Sub DynamicMenuStripItemBuilder(ByRef frm As Form, _
ByRef btn As
ToolStripDropDownButton, _
ByRef ds As DataSet, _
ByVal UserID As String)
For Each ctl In btn.DropDownItems
If ctl.GetType() Is Type.GetType("ToolStripMenuItem") Then
Dim mni As ToolStripMenuItem
mni = CType(ctl, ToolStripMenuItem) (SYNTAX ERROR)
Dim menuItem As New
ToolStripMenuItem(dr.Item("URLName").ToString, Nothing, New
EventHandler(AddressOf DynamicMenuStripItemHandler))
ctl.DropDownItems.Add(menuItem) (SYNTAX
ERROR)
End If
Next

Thanks,
Dean S
 
Back
Top