data interaction between 2 forms

Martijn van Dru

Newcomer
Joined
Jun 10, 2003
Messages
23
Hello all

I have the following problem. How can 2 forms interact wich eachother?
Code:
Public Class Form1
    Inherits System.Windows.Forms.Form

    Public myForm2 As New Form2()
    Public nData As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        myForm2.Show()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = nData
    End Sub
End Class

Public Class Form2
    Inherits System.Windows.Forms.Form

    Public nData As Integer
    Public myForm1 As New Form1()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        myForm1.nData = TextBox2.Text
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Me.Close()
    End Sub
End Class

In Form1 I create an instance of Form2. In Form2 I fill in an integer in textbox2 (nData). Now is my problem that I want that number nData in textbox1 on Form1, but I don't know how to do it. I don't wanna make a new instance of Form1, because then I have 2 different instances of Form1. Does somebody know in wich direction I have to search for my (simple?) problem?
thank you
 
try this...
Visual Basic:
Public Class Form1
    Inherits System.Windows.Forms.Form

    Public myForm2 As New Form2()
    Public nData As Integer

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '///
        Me.AddOwnedForm(myForm2) '/// add this line in form1
        '///
        myForm2.Show()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text = nData
    End Sub
End Class

Public Class Form2
    Inherits System.Windows.Forms.Form

    Public nData As Integer
    Public myForm1 As Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '///
        myForm1 = Me.Owner '/// add this in Form2.
        '/////
        myForm1.nData = TextBox2.Text
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Me.Close()
    End Sub
End Class
 
You could also setup a class with shared members so you wouldnt have to use the Owner property and you would not have a problem accessing the form instances from anywhere in the program.
 
Back
Top