Invalid Conversion error-Collection of common programming errors
You are iterating over all controls that are directly inside the form, not just the MenuItem
s. However, your variable is of type MenuItem
. This is causing the problem.
For normal controls (e.g. Button
s), 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 MenuItem
s 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.