Thursday, July 30, 2009

How to make an array or object global to all forms in Visual Basic?

I made a string array and all my subroutines in the original form could access it, but then I made another form, and that form couldn't access the array. So I made a class that would hold the array, thinking that if I did this it would solve my problem, but it didn't.





So how can I make my class (or array) visible to the other form?

How to make an array or object global to all forms in Visual Basic?
What you really did was make a module level variable. Module level provides access within the form only.





To make a program wide global variable you first need to add a module. Declare a Public variable at the top of the form and it will be available to any and all forms in the project.


Edit:


However if the form is closed you will loose the Public variable and its contents as well. By decalring a public variable in a module the module is available for the life of the project.


End Edit:





You may need to use the name of the module and variable in dot notation. For example a module named myMod with a Public Variable called myVariable is assigned the value of 10 in a form.





myMod.myVariable = 10





Global variables do have their uses but be aware that it is easy to inject errors into your project by inadvertently modifying a global variable. You cannot encapsulate a global variable with validation code like you can if you create a public property or public sub/function.








You said that you placed an array inside a class. You can declare a global variable as that class and use the encapsulation within the class to protect the values contained within. The global "Class" variable would then be accessable through out the project you would have to take care to initialize it at program startup when your main form loads.

botanical garden

No comments:

Post a Comment