Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom constructors for forms in vb.net: Best practices

I'm quite new to vb.net, and windows forms developement as a whole, so this might all be very basic, but here goes.

I would like to open a new form from some other form, and pass some selected object from a control on that form to the new form. The sensible way to do this, I thought, was as a parameter to the forms constructor. Now I know that the visual studio GUI creates partial classes for my forms, that hold the properties that I can drag onto there in the designer. I assume it also holds a default constructor. Since it might do all sorts of stuff that is needed to initialise the form, I figured I should call it from my custom constructor ala

public sub new(byval my_parameter as Foo)
  Me.new()
  Me.my_parameter = my_parameter
  do_some_initialisation()
end sub

That clearly wasn't it, because it can't find a default constructor. The thing is, visual studio goes trough great lengths to prevent me from seeing the generated constructor, so I know how to access it. This leads me to believe that I am actually doing it wrong, and should have set out on some different path, as the path you are forced in to usually is the sensible thing to do, which I usualy find out way too late.

So how should I be doing something like this?

like image 534
Martijn Avatar asked Nov 01 '10 14:11

Martijn


3 Answers

This is a fairly simple example. This goes into your "main" form (the one you want to call your new form from):

Dim childForm1 As New form2Name(item)
childForm1.Text = "Title of your new form"
Call childForm1.Show()

form2Name(item) breaks up like "form2Name" is the name of the form you want to open and "item" is the parameter to be passed.

In your new form (form2Name) add this code:

Public Sub New(ByVal item As String)
    InitializeComponent() ' This call is required by the Windows Form Designer.
    MsgBox(item)
End Sub

You can do whatever else you need in your form. Hope this helps.

like image 185
wergeld Avatar answered Nov 11 '22 02:11

wergeld


For VB.Net I think the call you are after is

MyBase.New()
like image 28
Chris W Avatar answered Nov 11 '22 01:11

Chris W


Your derived form class automatically inherits the default constructor for System.Windows.Forms.Form. This default constructor is invoked automatically before your derived constructor code executes. The reason you can't find any code for the default constructor is because the derived class does not specialize the default constructor. If you wish to define your own default constructor, you may. You can also define a constructor without parameters.

You code should work fine if you remove this line:

Me.New()
like image 2
Paul Keister Avatar answered Nov 11 '22 03:11

Paul Keister