Question Is Form1 special?

ianr900

Member
Joined
Jul 13, 2006
Messages
18
Location
UK
Programming Experience
3-5
If I create a new form, say Form2, in order to use it in a programme I must create an instance of it:

VB.NET:
Dim frmTwo and new Form2
If Form2 has a text box on it I can put this code in Form1:

VB.NET:
frmTwo.Textbox1.Text="Hello"
But what happens if I want to refer to an object (a text box)in Form1 with code in frmTwo? This doesn't work:

VB.NET:
Form1.TextBox1.Text="Goodbye"
How is the instance of Form1 created? And How do I refer to it?
Can someone explain this before I pull all my hair out!

Thx.
 

ctrlaltphreak

Member
Joined
Mar 28, 2008
Messages
10
Programming Experience
1-3
You could override the New() sub in form2 to take an instance of form1 as an arguement.

e.g.
Private myParent as Form1

Public Sub New(frmParent as Form1)
Me.InitializeCompontment
myParent=frmParent
End Sub

In Form1 replace Dim frmTwo and new Form2 with Dim frmTwo and new Form2(Me)

You could then refer to form1 through myParent. (e.g. myParent.TextBox1.Text="foo")
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
Another thing you can do is when you open Form2, pass a reference to Form1 when you show Form2:
VB.NET:
Dim frmTwo As New Form2
frmTwo.Show(Me)
Now in Form2 when you need to do anything with Form1 use: Me.Owner
VB.NET:
'A property that casts the generic Owner to your actual Form1:
Private ReadOnly Property ParentForm() As Form1
  Get
    Return DirectCast(Me.Owner, Form1)
  End Get
End Property
 
Top Bottom