JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Using Properties to Communicate between Forms

Besides the direct approach in the previous topic, another way to communicate between forms is to use properties, which we first saw in Chapter 3. For example, I can modify the example in the previous topic by adding this code to create a property named TextData to Form2, which gets or sets the text TextBox1:

Property TextData() As String
        Return TextBox1.Text
    End Get
    Set(ByVal Value As String)
        TextBox1.Text = Value
    End Set
End Property

Then I can use that properly to recover the text from the second window, like this:

    Dim OtherWindow As New Form2()

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
       TextBox1.Text = OtherWindow.TextData
    End Sub

Using properties is a better way to communicate between forms than accessing another form's data directly, because it gives you a well-defined interface. Instead of reaching into the code for Form2 and getting the text straight out of its text box, you use the Get and Set methods in the TextData property to get and set the text in the text box, which means you can test the data going into the text box, and return an error if you want to reject it.

Related solution:

Found on page:

Creating Properties


Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor