Apostrofix
Apostrofix

Reputation: 2180

How to update parent form from child form in vb6?

I have a parent form that opens a modal child form. The child form has 2 buttons - okay and cancel. I would like to call the corresponding events in the parent form. Any ideas how I can do that?

I thought that I have to pass the parent form object when calling Show on the child, but it doesn't seem to help.

This is the code that I have in the parent form:

answerFromChild = "NothingReceivedYet" 'it's a public property that should get updated 
                                         'to "Okay" when the okay button 
                                         'in the child form is clicked.

Dim myChildForm2 As New ChildForm2
myChildForm2.setVariableOne = "Test"
myChildForm2.Show vbModal, Me

If answerFromChild <> "Okay" Then Exit Sub

'there is more code if it says "Okay"

The above code in the parent works, but the answerFromChild property never gets updated to "Okay".

This is the code in the child form:

Private Sub Okay_Click()
    ParentForm1.answerFromChild = "Okay" 'this works but it updates 
                                         'the "answerFromChild" in 
                                         'another instance of the ParentForm1
    Unload Me
End Sub

Upvotes: 0

Views: 1839

Answers (1)

joehanna
joehanna

Reputation: 1489

A better design would be to declare a Public Event on the child form that the parent adds handlers for. Then you RaiseEvent in the child and that will trigger code execution in the parent which should then update its own form elements.

In child:-

'Declare the event that will broadcast the message to whoever is listening
Public Event SomethingImportantEvent(message As String)

Private Sub CommandButton1_Click()
  'Tell whoever is interested
  RaiseEvent SomethingImportantEvent("Hello from child")
End Sub

In parent:-

Dim WithEvents child As Form2

Private Sub child_SomethingImportantEvent(message As String)
  Debug.Print "The child said: " & message
End Sub

Private Sub CommandButton1_Click()
  If child Is Nothing Then
    set child = New Form2
  End If
  child.Show
End Sub

Upvotes: 2

Related Questions