Reference parent form elemets by child

P

Prashwee

Hi All

I got a small problem with VB 2005

I have let's say Form1 .Form1 has a Text Box1 and a Button1. When I click
the Button1 in a Form1, Form2 opens which has a button2 and a text box2 as
well.
When i click the button2 in the Form2 , Form2 should close and value in the
text box2 should be copied to Form1 Textbox1.
I know that I have to pass the Text box control to Form2 constructer when I
open the Form2

But what is the standard way of doing this?

Can you reference the Form1 current instance in some way?

/Best Regards
PRash
 
G

Guest

PRash,

In VB2005, from Form2 you can reference the textbox on Form1 like this:

Form1.Textbox1.Text = "Hello"

In VB2005 you do not need to pass a reference to Form1 in Form2's constructor.

Kerry Moorman
 
P

Phill W.

Prashwee said:
When i click the button2 in the Form2 , Form2 should close and value in the
text box2 should be copied to Form1 Textbox1.
I know that I have to pass the Text box control to Form2 constructer when I
open the Form2

But what is the standard way of doing this?

Forms are classes so, if you want to manipulate one (like handing it a
value), you have to have a reference to it.

When you open Form2, pass it a reference to Form1.

Class Form2
Public Sub New( ByVal oCaller as Form1 )
Me.New() ' run all the stuff created by the Designer
m_oCaller = oCaller
End Sub

Protected Overrides Sub OnClosed()
m_oCaller.TextBox1.Text = Me.TextBox2.Text
End Sub

Private m_oCaller As Form1

End Class

HTH,
Phill W.
 
C

Chris Dunaway

Phill said:
Forms are classes so, if you want to manipulate one (like handing it a
value), you have to have a reference to it.

When you open Form2, pass it a reference to Form1.

Class Form2
Public Sub New( ByVal oCaller as Form1 )
Me.New() ' run all the stuff created by the Designer
m_oCaller = oCaller
End Sub

Protected Overrides Sub OnClosed()
m_oCaller.TextBox1.Text = Me.TextBox2.Text
End Sub

Private m_oCaller As Form1

End Class

Another option is to add a property to your form2 and access that in
Form1:

Class Form2

Public Property SomeString As String
End Property

End Class

Then in Form1, you can access that property after closing form2
(assuming you opened it with ShowDialog).
 
R

RobinS

Or add a public method to Form1. Call it from Form2
and pass textbox2.text to the method.
The method in form1 would take a string and stuff it into the
appropriate textbox.

Robin S.
-----------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top