Please help me to understand how to use class to share variables.
I have 3 forms and one class to store some variables. Inside form1 I am calling myclass and setting up variables. Now I show form2 and inside form2 I call form3
Is it possible to get variable from a class , which I have sent from first form ?
Myclass code looks like this :
Private _var As String
Public Sub setvar(ByVal var As String)
_var = pvar
End Sub
Public Function getvar() As String
Return _var
End Function
from form1 :
Public class1 As myclass
class1 = New myclass
class1.setvar("test")
Now I want to call class1.getvar and I want it return the value which I have entered in a first form. is it possible ? if yes please help me how ?
Thanks
Because you have used the ‘Public’ access modifier on you ‘class1’ variable definition you should be able to access it as a field on Form1 from anywhere that has access to that instance of Form1.
It would probably be neater not to do it this way though.
OPTION1
If it were me I would prefer to create the instance of MyClass in the first form and then pass that instance to the other forms (possibly through the constructor).
End Class
Modify the New method of Form2 and Form3 to accept a parameter of type MyClass:
Then you are passing the variable in when you create the new form and storing it in a private member that you can access anywhere in the code of the second form.
OPTION2
Alternatively, you could put the definition of class1 into a module and then you could access it from wherever you want in the project.