Click here to Skip to main content
15,915,742 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanted a sub to create child forms but i am having issues
VB
Private Sub CreateChild(frm As Form)

    Dim frmChild As New frm
    frmChild.MdiParent = My.Forms.frmNavigation
    frmChild.Show()
    frmChild.Tag = My.Forms.frmNavigation.intTabCounter
    frmChild.FormBorderStyle = FormBorderStyle.None
    frmChild.ControlBox = False
    frmChild.MaximizeBox = False
    frmChild.MinimizeBox = False
    frmChild.ShowIcon = False
    frmChild.Text = ""
    frmChild.Dock = DockStyle.Fill

End Sub


Wondered if anyone can nudge me in the right direction.

I feel it's because i am trying to Dim as New but i am passing it the form i want to Dim a New of.

What I have tried:

I thought maybe i could pass the Forms name through as a string and then somehow loop through my forms for one matching that name, then Dim as New. Problem seems to be i can only loop through open forms.
Posted
Updated 8-Jun-17 8:30am

1 solution

Try using a generic method:
VB.NET
Private Sub CreateChild(Of TForm As {Form, New})()
    Dim frmChild As New TForm()
    ...
End Sub

To call it, you need to specify the type of form you want to create:
VB.NET
CreateChild(Of YourCustomForm)()

The type must inherit from Form, and must have a public parameterless constructor.

Generic Types in Visual Basic (Visual Basic) | Microsoft Docs[^]
 
Share this answer
 
v2
Comments
BeginnerCoderPete 8-Jun-17 16:11pm    
I seem to be getting an error on ,New) saying it is not a valid identifier. I am currently reading through the link you provided. Thank you
Richard Deeming 8-Jun-17 16:14pm    
Sorry, I misread the link. You need curly braces around the constraints when you have multiple constraints:
(Of TForm As {Form, New})
BeginnerCoderPete 8-Jun-17 17:50pm    
I have a public variable on the form i am opening as a child, would it be possible to also pass that into this sub to pass to the child form that's created?
Richard Deeming 9-Jun-17 6:43am    
You'd need to declare the property in a base class or an interface, and have your forms inherit from the base class or implement the interface.

Then you'd add the base class / interface as a constraint on the method:
(Of TForm As {BaseClass, New})
(Of TForm As {Form, IInterface, New})


You'll then have access to the members of that base class / interface within the method.
BeginnerCoderPete 9-Jun-17 8:08am    
Thank you for your reply, at the moment i'm finding it difficult to get my head around so i will have to spend sometime reading up on this. Really appreciate the help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900