Search code examples
vb.netclassinstances

How do I create a usable form instance?


I have tried making instances of forms, but none of them have worked.

This code works and turns the "lamp" on and off:

Public Class Lamp
    ' declare field
    Private lampColor As Color

    Public Sub New()
        ' initialize field
        lampColor = MainForm.lampShape.FillColor
    End Sub ' New

    Public Sub Switch()
        ' determine if lamp is on or off
        If lampColor = Color.Silver Then
            ' turn on lamp
            lampColor = Color.Yellow
        Else
            ' turn off lamp
            lampColor = Color.Silver
        End If

        ' display color on lamp
        MainForm.lampShape.FillColor = lampColor
    End Sub ' Switch
End Class

This code does not work:

Public Class Lamp
    ' declare fields
    Private lampColor As Color
    Private main As New MainForm

    Public Sub New()
        ' initialize field
        lampColor = main.lampShape.FillColor
    End Sub ' New

    Public Sub Switch()
        ' determine if lamp is on or off
        If lampColor = Color.Silver Then
            ' turn on lamp
            lampColor = Color.Yellow
        Else
            ' turn off lamp
            lampColor = Color.Silver
        End If
        ' display color on lamp
        main.lampShape.FillColor = lampColor
   End Sub ' Switch
End Class

I have tried this with many other projects too and none of them work.


Solution

  • Since your class never SHOWS the main it created, yet you say you can see the "square" not change color, you very likely have 2 instances of the form in use: the one that the VB app framework creates as a Startup form, then the one you create in the Lamp class. Add main.Show() to your constructor (sub New) and I bet you'll see a second form.

    From comments:

    After I did that, two forms are now opened

    The keyword New creates a new object. So, while your second class does use a form instance, it created its own New one which is a different one than the one VB created and showed.


    Assuming that form is the app's main form, and the form creates the class, this is what you want:

    Public Class Lamp
        Private lampColor As Color
        Private main As MainForm           ' no New!
    
        Public Sub New(frm As MainForm)
            main = frm                     ' store reference to the form passed
    
            lampColor = main.lampShape.FillColor
        End Sub ' New
        ...
    

    Then when you create it:

    Public Class MainForm
       Private myLamp As Lamp            ' just declare it
       ...
       ' in form load:
           myLamp = New Lamp(Me)             ' pass this form inst to the lamp object