如何在vb6中从子表单更新父表单?

时间:2015-08-20 09:29:08

标签: forms vb6

我有一个父表单,可以打开一个模态子表单。 子表单有2个按钮 - 好的,取消。我想在父表单中调用相应的事件。我有什么想法可以做到吗?

我认为在为孩子调用Show时我必须传递父表单对象,但它似乎没有帮助。

这是我在父表单中的代码:

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"

父作品中的上述代码有效,但answerFromChild属性永远不会更新为&#34;好的&#34;。

这是子表单中的代码:

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

1 个答案:

答案 0 :(得分:2)

更好的设计是在父表单添加处理程序的子表单上声明Public Event。然后你在子进程中RaiseEvent,这将触发父进程中的代码执行,然后应该更新自己的表单元素。

在孩子: -

'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

在父母: -

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