Passing Data to a New Form
For a Windows Forms application, creating a new form is as easy as Project / Add Windows Form / Windows Form. But what if you need to set this form up with some data that exists in the main form? How do you populate the controls and variables in the new form with the existing values from the main form?
This simplest way to set up a new form so that it includes some existing data from the main form is to create a custom constructor for the new form. That sounds much more fearsome than it really is. A custom constructor is simply a New sub that has an argument list that will contain the values that you need to pass to the new form, and which populates controls and variables on that form as required.
In this example, Form2 will need to get a customer name and a transaction date from the main form. The customer name will be copied into a text box, and the date will be saved into a form-level variable TDate. The Form2 constructor looks like this:
Public Sub New(ByVal CustName As String, ByVal TrxDate As Date) InitializeComponent() TextBox1.Text = CustName TDate = TrxDate End Sub
The dummy names used in the Sub declaration (CustName and TrxDate) can be anything at all, but they will appear in Intellisense when you write the code to instantiate the form (see below) so it is worthwhile choosing something meaningful. In this case the first argument will be copied to the text box TextBox1, and the second will be copied to the form-level variable TDate.
The form is instantiated and displayed from the main form with:
Dim frm As Form2 = New Form2(Customer, thisDate) frm.Show
where Customer is the customer name and thisDate is the transaction date. The end result is that the value in Customer is copied into the TextBox1 control on Form2, and the date in thisDate is copied into the variable TDate in Form2.
This process would be considered adequately robust because, although it requires that the main form know the information required by the second form, that requirement is enforced in the constructor.