The sample below uses two forms:
- form1 is the main form, and has a button to launch Form2, and a textbox
- form2 is the subform, and has a button that set's a text in the textbox on the main form Form1
First, Create Form1 and Form2.
We now need to add a parameter to Form2, which can be used to refer back to form1. Doubleclick in the desginer on form2, and modiy the class as folows:
Public Class Form2
Public callerform As Form1
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End ClassWe now have a callerform property of the type form1, which can be used to add a reference back to the correct instance of form1 (you could have 10 open in an mdi application all named form1, but with different data)
Next, we need to add the code to the button on Form1, and make it so that it passes itsself as a reference to Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim newform As New Form2 ' create a new instance of form2
newform.callerform = Me ' add the handle to the opening form
newform.Show() ' open the new form2
End SubLast, we modifie the button on the form2 to use the passed handle to set a text on the calling form
Private Sub ButtonOnForm2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonOnForm2.Click
Me.callerform.TextBox1.Text = "Hello Callerform!"
End Sub