Vb.net Passing a text field between forms.
I have 2 forms. In Form1, I want to pass the value of a textbox to form 2 on load. This is what I thought would work. Form1 will be loaded and launched, and the data will be filled in form1. I am expanding the textbox property on form1. Then I try to use this public property on form2.
Public Class form1
Public ReadOnly Property GetTextBox() As String
Get
Return txtbox1.Value
End Get
End Property
In shape 2
Dim X As form1
Me.TextBox1.Text = X.GetTextBox
source to share
There are several ways to dump this cat.
The simplest would be to create a second (or replace the existing) constructor for Form2
that takes string
as a parameter. Then, when it Form1
creates Form2
, you can pass the argument this way.
Public Class Form2
Sub New(ByVal txt As String)
InitializeComponent()
Me.TextBox1.Text = txt
End Sub
End Class
Then in Form1
you will have something likeDim f2 As Form2 = New Form2(myTextBox.Text)
In other ways, to be honest, basically the same as this, except that you could pass yourself Textbox
as an argument to a constructor, or even Form1
assign Dim X As Form1 = theForm
in a constructor. Generally speaking, if you don't need anything more than simple Textbox.Text
, then you should only accept string
in a constructor. There is no reason to reveal full control or form if you don't need it all!
Your current code is pretty close, but since Plutonix commented on your property Form2
X
, this is just another instance Form1
, not the actual instance displayed by the application.
source to share
VB will allow you to reference form instances by their class name , so you can use:
Me.TextBox1.Text = Form1.GetTextBox
However, you should not rely on this and should instead pass an explicit instance Form1
to Form2
eg. in the constructor:
' Form2
Public Sub New(ByVal f As Form1)
Me.New()
' save 'f' for future reference
End Sub
source to share
When you do this:
Dim X As form1
You create a new link to form1
. (And presumably by creating it somewhere, or perhaps relying on a function in VB that uses the default form instance . Trust me, don't do that.) This instance is completely unrelated to an instance that already exists. What you are looking for is a reference to an instance that already exists.
If it form2
has a dependency on form1
and requires an instance reference form1
, then this constructor reference is required for form2
:
Private Property Form1Instance As form1
Sub New(ByVal form1Instance As form1)
Me.Form1Instance = form1Instance
End Sub
When you instantiate your instance form2
, provide it with an instance reference form1
:
Dim form2Instance As New form2(Me)
form2Instance.Show()
Then in form2
you can refer to an existing instance form1
:
Dim someVariable As String = Me.Form1Instance.GetTextBox()
source to share