Search code examples
vb.netmdichild

Calling the same function on eterogene MdiChild FormVB.NET


I have a list of eterogene MDIChildForms (MyChild1, MyChild2, ...) in my MDIParent. All of this form have a public function myFunction(p As myType). I would like to loop them and for each one call myFunction.

Pseudocode:

For Each myChild In Me.MdiChildren
     myChild.myFuntion(p)
Next

Is it possible? How can I do that? Thanks


Solution

  • You should define an interface that declares that method and then implement that interface in each child form class.

    Public Interface ISomeInterface
    
        Sub SomeMethod()
    
    End Interface
    
    Public Class Form1
        Implements ISomeInterface
    
        Public Sub SomeMethod() Implements ISomeInterface.SomeMethod
            '...
        End Sub
    
    End Class
    

    You can then cast each form as that type and call the method, e.g.

    For Each mdiChild As ISomeInterface In MdiChildren
        mdiChild.SomeMethod()
    Next
    

    That assumes that every form implements that interface. If some don't, you can do this:

    For Each mdiChild In MdiChildren.OfType(Of ISomeInterface)()
        mdiChild.SomeMethod()
    Next