Student Student - 5 months ago 26
Vb.net Question

VB.NET What is the best way to pass value to another form?

I have two form which uses the same connection string such as,

Dim connStr as String = "Server = localhost; Database = tester; Uid = root; Pwd = 123"


The code above is placed in Form1. So in my Form2, I will be using the same connection string again. Instead of copy and paste it again to every next form, what is the best way to do it?

I have tried using this code,
Public Property connString as String = "bla..bla"
for Form2. Then in Form1, I let it hold the same string like this
Form2.connString = connStr


Is this the right way to pass value between forms? Or is there a proper/better way to do it?

Answer

The best way to pass or call a variable from different forms is to create a module.

Open Visual Studio, click PROJECT from the menu bar > Add Module... > Select Module > OK

From there, you can declare your GLOBAL VARIABLES.

Module Module1
   Public connStr as String = "Server = localhost; Database = tester; Uid = root; Pwd = 123"    
End Module

The variable "connStr" can now be called from different forms.

From your Form1 and Form2 you can just call this GLOBAL VARIABLE as if they are your local variables.