New instance of a Window

I have a button at frmMain that creates a instance of a frmTemplate (which is a Window or Form if you wish)

Dim frmInstance As New frmTemplate instanceShown = True // this is a property I will set to false once frmTemplate Close event fires in order for me to control whether the window is opened or not

Clicking the button again creates a new instance (indefinitely) but I just want to .show the frmTemplate (or setFocus on it) rather than creating a new Window.

I tried creating frmInstance as a frmMain property which works as desired, however, on button click I also need to set some properties on frmInstance and this way it will just not work properly (dunno why).

Instead of creating a new window each time you could just use .show :slight_smile:

Or check to see if instanceShown is true and only create a new window if it’s false.

If instanceShown = False Then
Dim frmInstance As New frmTemplate
instanceShown = True
End if

lol, okay I have multiple buttons :stuck_out_tongue: they launch the same window with different content

edit: many many buttons :smiley:

I think I found a workaround:

Just need to open the instanced window with visible=false, set his properties, and only then do a visible = true

This works with the Window as a property of frmMain so I can handle it better this way

edit: Unfortunately I cannot set instanced properties from frmMain, only change object properties. It’s okay

Why not? This should work fine.

@Tim Hare I can only set form related properties, this excludes variables (global properties) etc

For instance frmTemplate has a Label1 which I cannot handle from frmMain on button click

This is a scenario where frmInstance is a Window type property of frmMain

ButtonClick Event Code:

frmInstance = New frmTemplate frmInstance.Label1.Text = "Test" // *

  • not working, error (This item does not exist, highlighting frmInstance.Label1)

Wierd. Should work as Tim said.
One other alternative is to pass parameters through the Constructor. Could that work for you?

How is frmInstance declared?

frmInstance as frmTemplate

  • or -
    frmInstance as Window

If the latter, then you have to cast to get at the contents specific to the window.

if frmInstance IsA frmTemplate then
   frmTemplate(frmInstance).Label1.Text = "Test"

Is as Window.

It’s working now! (without the Dim)

Tim thanks for the free “IsA” tip!

Okay, after two hours on this the best solution is a mix of Tim’s answer with Albin’s answer :wink: