Pushing Results Back to the Main Form
Even if you identify the form that opened a subsidiary form, it’s not always easy to update controls on the form with new values. This snippet shows how it is done.
To be able to return values from the subsidiary form to the calling form, you first need to identify that form – the Where Did I Come From snippet shows one way to do that. But it is not always possible to update controls on that form to correctly represent values that change on the subsidiary form. In fact, it is not good practice to directly manipulate properties of a control on another form. But it is quite easy to do it indirectly.
The process involves creating a Property of the main form with scope of Public or Friend. When this property is updated with a new value, the setting of the control is also updated. In this example we will expose two control settings as properties – a textbox Text setting and a progress bar Value setting.
Public WriteOnly Property UpdateValue() As Double Set(ByVal value As Double) ProgressBar1.Value = value End Set End Property Public WriteOnly Property UpdateText() As String Set(ByVal value As String) Label1.Text = value End Set End Property
The above code creates two properties of the main form – an UpdateValue property that takes a double value and which sets the progress bar to that value, and an UpdateText property that takes a string and sets the label Text property to the string. The code in the subsidiary form would look like this:
MyParent.UpdateValue = Temperature If Temperature > 90 Then MyParent.UpdateText = “Over Range!!” End If
This process would not be considered robust because, although it disconnects the subsidiary form from the details of the controls on the main form, it still requires that the subsidiary form has a reference to its calling form, and that the subsidiary form knows that its parent actually has a UpdateValue and a UpdateText property. The code in the subsidiary form is therefore dependant on other forms in the application, and this means it is not as general as it could be. For a procedure that avoids this problem, see Messaging Between Forms.