我有Form1和Form2。我想从Form2 Form1中调用函数 但它不起作用。我使用Visual Studio 2015。
Public Class Form1
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim form As New Form2
form.Show()
End Sub
Public Sub Test()
TextBox1.Text = "Hello"
End Sub
End Class
Public Class Form2
Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim form As New Form1
form.Test()
End Sub
End Class
答案 0 :(得分:0)
当您在Form1
点击按钮时,您正在创建另一个Form2
,这不是您的父表单。您需要在创建时指定Form2
的所有者,然后您可以引用它。像这样:
<强> Form1中:强>
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim form As New Form2
form.Show(Me) 'I am assigning Form2's Owner here
End Sub
Public Sub Test()
TextBox1.Text = "Hello"
End Sub
End Class
<强>窗体2 强>
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CType(Me.Owner, Form1).Test() 'Casting Form2's Owner to Form1 to access your sub
End Sub
End Class