Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I declare a global variable in Visual Basic?

Tags:

vb.net

I want to create a variable that can be used across multiple forms.

It's going to be a temporary storage place for integers.

like image 481
user3470747 Avatar asked Mar 29 '14 23:03

user3470747


People also ask

How do you declare a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

What is used to declare a variable in Visual Basic?

Option Explicit statement You can implicitly declare a variable in Visual Basic simply by using it in an assignment statement. All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables.

Where we can declare global variable?

Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.


2 Answers

There are a couple of ways to do this in VB: a VB-specific way and a non-VB specific way (i.e. one that could also be implemented in C#.

The VB-specific way is to create a module and place the variable in the module:

Public Module GlobalVariables
   Public MyGlobalString As String
End Module

The non-VB-specific way is to create a class with shared properties:

Public Class GlobalVariables
  Public Shared Property MyGlobalString As String
End Class

The primary difference between the two approaches is how you access the global variables.

Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:

MyGlobalString = "Test"

For the non-VB-specific way, you must prefix the global variable with the class:

GlobalVariables.MyGlobalString = "Test"

Although it is more verbose, I strongly recommend the non-VB-specific way because if you ever want to transition your code or skillset to C#, the VB-specific way is not portable.

like image 68
competent_tech Avatar answered Oct 09 '22 22:10

competent_tech


IN VB6 just declare on top code

public GlobalVariable as string

then you can use GlobalVariable in any form as you like.

like

GlobalVariable = "house"

then you can use /call in other form

text1 = GlobalVariable

will show value "house"

like image 23
Yusuf Efendy Avatar answered Oct 09 '22 21:10

Yusuf Efendy