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 but 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 typeMenuItem. 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:However, this does not work for
MenuItems since these aren’t controls at all in WinForms, and they aren’t stored in the form’sControlscollection.You need to iterate over the form’s
Menu.MenuItemsproperty instead.