Reputation: 1338
I am trying to loop through all of the controls in a panel. Some of the controls as classes that I created. In those classes, I want a subroutine run when the object is removed. So I am trying to create a temporary object that I can use to run that routine.
For Each window As Control In main_window.Controls
If window.Handle = hdl Then
Dim temp_window as window.getType()
temp_window.close_me()
main_window.Controls.Remove(window)
End If
Next
However, the getType assignment is not allowed.
How can I accomplish this?
Upvotes: 1
Views: 531
Reputation: 2474
The right way to do this is to use a base class that your controls Inherit
or an interface that your controls Implement
with close_me
on the base or interface. Then, you can TryCast
each member of Controls
to the base or interface and, if it succeeds, call close_me
on it. If you use the base class approach, you may wish to make it abstract (MustInherit
) and then close_me
would be MustOverride
, depending on if the behavior should be different in each derived type.
e.g. assuming you use ICloseable
,
Interface ICloseable
Sub close_me()
End Interface
'...
For Each window As Control In main_window.Controls
If window.Handle = hdl Then
Dim asCloseable = TryCast(window, ICloseable)
If asCloseable IsNot Nothing Then
asCloseable.close_me()
EndIf
EndIf
Next
Upvotes: 0
Reputation: 460028
Object.GetType
is not what you want, it returns the Type
instance of the object which contains meta data of that type, normally used for reflection.
What is the actual type that you want? It has to have a close_me
method. You could use OfType
:
Dim windowsToClose = main_window.Controls.OfType(Of YourWindowType)().
Where(Function(w) w.Handle = hdl).
ToArray()
For Each window In windowsToClose
window.close_me()
main_window.Controls.Remove(window)
Next
Your For Each
doesn't work for another reason: you can't remove items from the collection while you are enumerating it. Above approach stores the windows you want to remove in an array.
Upvotes: 1