Link to home
Start Free TrialLog in
Avatar of alfardan
alfardanFlag for United Arab Emirates

asked on

Move Variables Values Between Forms

Hi

I have a form [Form1] that has a [Dim SomeVar as String = "Some_Value"]

Also, this form has a button that upon clicking then it hides [Form1] and shows [Form2]

How do I transfer/use this [SomeVar] value in [Form2] by then?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The best way to do that is to create a constructor in Form 2 that requires a parameter:

Public Sub New (yourVariable As String)
   InitializeComponent()
   'Do what you want with yourVariable
End Sub

It's important to leave the InitializeComponent, it calls the method that creates the form.

Then, in Form1, when you need to pass the value to Form2, do it the following way:

Dim form2 As New Form2(SomeVar)

Your variable will be passed to the form. You can pass many variables if needed, and even create many Sub New, which will give you many ways to initialize the form (this is called overloading), as long as the type of parameters (this is called the signature of the method) are different.

This is a better way than a Shared variable.

First, the shared variable is shared between different uses. That might not cause problems for now, but there are a few situations that could happen during maintenance (an application lives for a while, many years is most cases) where you will end up having strange bugs. There are uses for Shared variables, but this is not one of those.

Second, it becomes visible in all the application. Any form or module in the project will have access to it, even if not initialized by Form1. This can make debugging a lot more difficult because you might have to look everywhere in the application to correct some bugs. Passed as a parameters, the use is limited to where you intend it to be, and you will look more easily where to look for in case of bugs.