Variable Value Go to another form, VB.Net
I have two public variables, each with two different forms.
Form1.VB
Public UserNo As String
Form2.VB
Public MyUserNo As String
In my Form2.VB file I am assigning the UserNo value from Form1.VB
Form1.UserNo = MyUserNo
Whenever I access Form1.VB, the value MyUserNo is empty, what should I do? Both forms are not closed.
I have also tried to re-assign the value when I need to use it in Form1.VB
UserNo = Form2.MyUserNo
source to share
What you need to do is create your variables in the module as private and then create multiple evaluators for them.
Example:
Module modVariables
Private strUserNoSTR as String = New String(String.Empty)
Public Property getUserNoSTR() As String
Get
Return strUserNoSTR
End Get
Set(ByVal strUserNo As String)
strUserNoSTR = strUserNo
End Set
End Property
Private strMyUserNoSTR As String = New String(String.Empty)
Public Property getMyUserNoSTR As String
Get
Return strMyUserNoSTR
End Get
Set(ByVal strMyUserNo As String)
strMyUserNoSTR = strMyUserNo
End Set
End Property
End Module
After creating the public getter and setter methods, you may notice that your two private variables are inside them when you create variables that are accessible from any form.
The reason why you loose the value of variables is that when you try to access its value from another form (basically you call it from another class) the compiler has to create a new instance of that variable and when that happens the variable is returned to its original value, which is of type empty string
. Calling them from a module does not allow re-instantiation.
How to use them:
To get the strMyUserNo value, you call getter strMyUserNoSTR:
TextBox.Text = getMyUserNoSTR
To set the strMyUserNoSTR value:
getMyUserNoSTR = someValuePlacedInThisVariable 'This sets it value.
TextBox.Text = getMyUserNoSTR 'Now it value is someValuePlacedInThisVariable.
source to share