1

I have the following code in my Form1 wherein I will set Value to a property:

Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text

and this is my code from my logInSession class where I will store the value:

Private logInfo As String

Public Property saveLogInfo() As String
    Get
        Return logInfo
    End Get
    Set(ByVal value As String)
        logInfo = value
    End Set
End Property

Now, I want to get back out the value to my Form2. The problem is it doesn't return any value. The following is my code:

Dim login As New logInSession
Dim k As String
k = login.saveLogInfo
MsgBox(k)

Can you tell me what's the problem with my codes?

har07
  • 88,338
  • 12
  • 84
  • 137
slek
  • 309
  • 6
  • 17

2 Answers2

1
Dim login As New logInSession // HERE
Dim k As String
k = login.saveLogInfo
MsgBox(k)

This code creates a new instance of the logInSession class. Therefore, each time you are trying to access the login.saveLogInfo property, it is at it's default value (empty string). You need to use the original object you created here:

Dim login As New logInSession
Dim k As String
login.saveLogInfo = unameTB.Text
Inisheer
  • 20,376
  • 9
  • 50
  • 82
  • How to do that? Should I remove "New" in my code where I'm going to get the value? that will cause an error, right? – slek Feb 05 '14 at 03:26
  • 1
    @kels016 You are correct. Without seeing your entire code it's hard to say exactly how you should implement it. Typically, to pass data from one Form to another, you add an additional constructor to the Form2 class, such as Sub New(_logInSession As logInSession). You'd pass the original logInSession to Form2 from Form1 and store it within Form2. – Inisheer Feb 05 '14 at 03:31
  • thank you for giving me the idea. I used this as reference http://stackoverflow.com/questions/14419516/accessing-the-same-instance-of-a-class-in-another-form – slek Feb 05 '14 at 05:41
1

That's because you have two different instances of logInSession class. One in Form1 and another in Form2. Here is an illustration :

Dim login As New logInSession
'you have 1 logInSession instance here, and set it's property
login.saveLogInfo = "Some Text"

Dim anotherLogin As New logInSession
'but later you check property of another instance of logInSession
Dim k = anotherLogin.saveLogInfo
'here you get empty string
Console.WriteLine(k)

'you need to, in some way, pass the first instance instead of creating new instance
Dim referenceToFirstInstance As logInSession = login
k = anotherLogin.saveLogInfo
'here you get "Some Text"
Console.WriteLine(k)

Check this reference on how to pass data between forms

Community
  • 1
  • 1
har07
  • 88,338
  • 12
  • 84
  • 137