Accessing controls in another form

D

DaveG

Hi

Using VB.net 2003

I know how to access controls on a 2nd form after declaring the form in
the first.

But how do I access the controls on the original form from the 2nd form.

(in frmMain)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim form2 As New Form2
form2.TextBox1.Text = TextBox1.Text
form2.Show()
End Sub

(in Form2)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim form1 As New Form1
form1.TextBox1.Text = TextBox1.Text
form1.Update()
Me.Close()

End Sub


Form2 textbox updates ok
The textbox in form1 does not update and still holds the original text
before opening Form2

This is just a simple example I cannot get working, once I can get this
working the I should not have problems with the actual code I need to use.

There must be a simple answer to this....???

Thanks in advance for any help given

DaveG
 
M

Morten Wennevik

Hi Dave,

You need to pass a reference to your 1st form when declaring the 2nd, typically

Form2 f2 = new Form2(this); // Me in VB

Overload the constructor of the 2nd form to accept a 1st form parameter.
Store the parameter for later use
 
D

DaveG

Thanks Morten

Noe the problem is I have used the overload in normal funtions and subs
but never with the constructors, so now I'm a little lost, I understand
the reasons for the overload..... so the New form2(Me) will be excepted
bur how to implement it is where I am stuck......
 
M

Morten Wennevik

Dave, overloading a constructor is done the exact same way, although I'm not sure how the VB syntax is. Store the Form1 reference for later use.

private Form1 myParent;

public Form2(Form1 f)
{
myParent = f;
}

then simply call

myParent.MethodOrSimilarInForm1()

whenever you need.
 

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