This is my problem...
I have a form (Form1), which is calling another form(Form2). In this Form2, when I close the Form, I want to call a method of Form1, to change values from Form1 components. The method is called, but the components values of Form1 don't change... I guess this is because when I call the method of Form1 from Form2, it is created anothed Form1 instance, and the method it's not executed in Form1 from which I call Form2

Form1 calling Form2

Private Sub btnCallForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCallForm.Click
    frmForm2.ShowDialog()
End Sub

Form2 calling method of Form2

Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
   frmForm1.ChangeValues()
End Sub
有帮助吗?

解决方案

Pass the original instance of Form1 to the constructor of Form2, like this:

Public Class Form2 Inherits Form
    Dim theForm1 As Form1
    Public Sub New(form1 As Form1)
        theForm1 = form1
    End Sub

    Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOk.Click
        ' Call instance of Form1 passed in to change the values here
        theForm1.ChangeValues()
    End Sub
End Class

Now in Form1, when you create the Form2 instance you need to pass the instance of Form1, like this:

Dim frmForm2 As New Form2(Me) 
frmForm2.ShowDialog()

Note: Me is a reference to the current class, Form1 in this case.

其他提示

If you're not passing any values back in ChangeValues(), then simply call it after the ShowDialog() line. Then Form2 doesn't need to know about Form1 at all!...

Form1 calling Form2, then updating itself afterwards:

Private Sub btnCallForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCallForm.Click
    frmForm2.ShowDialog() ' <-- code stops here until frmForm2 is dismissed
    Me.ChangeValues() ' <-- we're already here, update the values!
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top