vb.net Pass Textbox Between forms.

I have 2 forms. On Form1 I want to pass the textbox value to form 2 on load. This is what I thought would work. Form1 will be loaded and running and data will be populated in form1. I am exposing the property of the text box in form1. Then I am trying to use that exposed property in form2.

Public Class form1

Public ReadOnly Property GetTextBox() As String
    Get
        Return txtbox1.Value
    End Get
End Property

On form2

 Dim X As form1
 Me.TextBox1.Text = X.GetTextBox

Solution 1:

There are a handful of ways to skin this cat.

The simplest would be to create a second (or replace the existing) constructor for Form2 that accepts a string as an parameter. Then when Form1 creates Form2 you can pass the argument that way.

Public Class Form2
    Sub New(ByVal txt As String)
        InitializeComponent()
        Me.TextBox1.Text = txt
End Sub
End Class

Then in Form1 you'd have something like Dim f2 As Form2 = New Form2(myTextBox.Text)

The other ways are honestly basically the same as this, except you could pass the Textbox itself as an argument to the constructor, or even Form1 and assign Dim X As Form1 = theForm in the constructor. Generally speaking, if you don't need anything more than just Textbox.Text then you should only accept a string in the constructor. No reason to expose an entire control or form if you don't need all of it!

Your current code is pretty close, but as Plutonix commented your Form2's X property is just another instance of Form1, not the actual instance that's being displayed by the application.