Hi,

I'm trying to pass a string from form1 to form2. The string will change dynamically change as it receive inputs in form1. I've tried some example on passing by property and passing by constructors. But, I can't read the string in the second form. Any pointers? Thanks.

Dan

Recommended Answers

All 4 Replies

There are many options for passing values.

01) you could use a public variable in a module file
02) You can pass it thru the constructor of the new form
03) You can create public properties in the new form and pass them thru that
04) You can access the data directly from the form1's controls

Sub Form2_Load()

myValue = Form1.TextBox1.Text

End Sub

if Form1 is still open then you can get the string just like Form1.Textbox1.text

you can also create a overloaded New() procedure in Form2 to hand over the sting like

Public Sub New (byval myString as string)
TextBox2.Text=myString
End Sub

and call the Form2 in Form1 like
Dim myForm as New Form2(TextBox1.Text)

You should avoid accessing the value directly, its bad practice (encapsulation).

You should create a private variable in Form2 and change its value through a public property:

'in form2:
Private _myProperty As String

Public Property MyProperty() As String
    Get
        Return _myProperty
    End Get
    Protected Set(ByVal value As String)
        _myProperty = value
    End Set
End Property

'inside a method on Form1:
Dim myForm As New Form2
  myForm.MyProperty = "text to pass to form2"

Encapsulation is one of the key elements of Object Oriented Design, as such, you should avoid exposing internal variables and controls directly.
Just my 2 cents :)

Hi all,

Thanks for helping. I've manged to get it right with the hints provided.
I've used Ryshad codes, but i ran into trouble of Protected. Well, it's at best to embrace OO, but sometimes it makes life difficult when it comes to mini application like what i'm doing. ;p

Thanks for help!

Dan

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.