Reputation: 147
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
Upvotes: 1
Views: 2940
Reputation: 8181
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.
Dim myString as String = form1.class1.getvar()
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).
Public Class Form1
Private _instance As MyType
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
_instance = New MyType
Dim newForm As New Form2(_instance)
End Sub
End Class Modify the New method of Form2 and Form3 to accept a parameter of type MyClass:
Public Class Form2
Private _instance As MyType
Sub New(instance As MyType)
_instance = instance
End Sub
End Class
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.
Upvotes: 2