schnefff boi
schnefff boi

Reputation: 1

How do I access a method from another form

I'm doing a projectile motion project and I want a live animation to play when you press a button. The button opens another form and to get the projectile to move I need to call a method from the first form

Public Class Projectile
    Public Sub UpdatePosition()
        Left = Left + 10
    End Sub
End Class

This is the code from the first form

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        For Each control As Control In Controls
            If TypeOf control Is Projectile Then

            End If
        Next
    End Sub

and this where I want to call UpdatePosistion to.

How can I do this?

Upvotes: 0

Views: 42

Answers (2)

Mary
Mary

Reputation: 15081

Your class needs Inherits Control or it will not be found in the Controls collection.

Cast the control to the type with the UpdatePosition method.

Public Class Projectile
    Inherits Control
    Public Sub UpdatePosition()
        Left = Left + 10
    End Sub
End Class

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    For Each control As Control In Controls
        If TypeOf control Is Projectile Then
            DirectCast(control, Projectile).UpdatePosition()
        End If
    Next
End Sub

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

We need to cast the control variable in the For Each loop and If block to a Projectile variable. We can simplify this using the OfType(Of T) method:

For Each control As Projectile In Controls.OfType(Of Projectile)()
    control.UpdatePosition()
Next

The OfType() call handles both the cast and If check for us.

Upvotes: 2

Related Questions