从Form2更改Form1的TextBox文本

时间:2013-12-11 01:01:51

标签: vb.net forms showdialog

这是我的问题......
我有一个表单(Form1),它调用另一个表单(Form2)。在这个Form2中,当我关闭Form时,我想调用Form1的方法,以更改Form1组件中的值。调用该方法,但Form1的组件值不会改变...我想这是因为当我从Form2调用Form1的方法时,它创建了一个带有Form1的实例,并且在Form1中没有执行它的方法我称之为Form2

Form1调用Form2

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

Form2的Form2调用方法

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

2 个答案:

答案 0 :(得分:2)

Form1的原始实例传递给Form2的构造函数,如下所示:

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

现在在Form1,当您创建Form2实例时,您需要传递Form1的实例,如下所示:

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

  

注意:Me是对当前类的引用,在这种情况下为Form1

答案 1 :(得分:0)

如果你没有在ChangeValues()中传回任何值,那么只需在之后将其称为 ShowDialog()行。那么Form2根本不需要了解Form1!...

Form1调用Form2,然后更新本身

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