share variables

johmolan

Well-known member
Joined
Oct 11, 2008
Messages
129
Programming Experience
Beginner
Is it possible to share a variable between 2 or more forms. How?
I am grateful for all answers.
 
First up, you're making the classic mistake of treating forms as though they are different to other objects. They aren't. They follow the exact same rules as any other object as far as accessing variables.

So, in order for two objects to access the same data, that data must be in a location that both objects can see it. If you want every object in your project to be able to see some data then there are two ways to do it:

1. Expose it via a Shared member of a class.
2. Expose it via a member of a module.

They actually amount to the same thing once your code is compiled but differ slightly in code. The second option is the most commonly used, particularly by beginners. E.g.
VB.NET:
Module MyModule

    Public myData As String

End Module
You can now access myData from anywhere in your project.

That said, global variables are generally something to be avoided. They have their place but are generally over-used by beginners. There are generally "more correct" ways to get data from one object to another. If you explain what exactly it is you're trying to achieve, i.e. the relationship between these two forms, then we can probably advise as to what the "most correct" course of action would be.
 
Another beginner mistake is to think something needs to be available everywhere at all times to be able to use it when they need it, when usually there is a natural execution flow where you pass on values as parameters to methods or get/set values between class instances via common instance properties. When something actually should be or is easiest globally shared, an alternative to Shared class members may be using Application Settings. jmcilhinney advice and inquiry is of course all right too.
 
Back
Top