开发者

Invalid Conversion error

开发者 https://www.devze.com 2023-03-08 02:45 出处:网络
I recently upgraded a VB 6 project to .net. I\'m having a problemwith this block of code: Dim CtrlName As System.Windows.Forms.MenuItem

I recently upgraded a VB 6 project to .net. I'm having a problem with this block of code:

    Dim CtrlName As System.Windows.Forms.MenuItem

    For Each CtrlName In Form1.Controls

    'Some code here

    Next CtrlName

Now this code compiles bu开发者_JAVA百科t throws the following runtime error:

Unable to cast object of type 'System.Windows.Forms.Panel' to type 'System.Windows.Forms.MenuItem.

I have a panel control on the subject form. How do I resolve this? Thanks.


You are iterating over all controls that are directly inside the form, not just the MenuItems. However, your variable is of type MenuItem. This is causing the problem.

For normal controls (e.g. Buttons), you’d want to use the following, easy fix; test inside the loop whether the control type is correct:

For Each control As Control In Form1.Controls
    Dim btt As Button = TryCast(control, Button)
    If btt IsNot Nothing Then
        ' Perform action
    End If
Next

However, this does not work for MenuItems since these aren’t controls at all in WinForms, and they aren’t stored in the form’s Controls collection.

You need to iterate over the form’s Menu.MenuItems property instead.


The items in the Controls property of a form, which may or may not be MenuItem. Assuming that you just want to iterate over MenuItem objects you can change your code to:

For Each menuControl As MenuItem In Me.Controls.OfType(Of MenuItem)
  ' Some code
Next

Note that the menuControl variable is declared in the For so is only accessible within the block and is disposed automatically.


for each ctrl as control in me.controls
 if typeof ctrl is menuitem then
   ' do stuff here
 end if
next

typeof keyword allows you to test the type of control being examined in the control collection.

Found the answer after a bit of research, you need to search for the menu strip first and then loop through the items collection.

 For Each ctrl As Control In Me.Controls
  If TypeOf ctrl Is MenuStrip Then
            Dim mnu As MenuStrip = DirectCast(ctrl, MenuStrip)
            For Each x As ToolStripMenuItem In mnu.Items
                Debug.Print(x.Name)
            Next    
        End If
    Next
0

精彩评论

暂无评论...
验证码 换一张
取 消