vb.net 如何从子表单访问父表单属性

How to access parent form properties from a child form in vb.net

我遇到的问题与 this 中描述的几乎相同,但使用的是 VB.NET。有一个 Form1 自动打开为开始 window,所以我找不到用于访问它的实例。从 Form1 中打开了一个 Form2。我尝试使用关键字“Me”传递 Form1 的实例:

Private Sub Button1_click(...) Handles Button1.Click
 Dim childform as new Form2(Me)
 childform.show()
End Sub

在 Form2 中我有:

Public Sub New(parentform As System.Windows.Forms.Form)
 InitializeComponents()
 MessageBox.Show(parentform.Button1.Text)
End Sub

编译时出现错误:“Button1 不是 Form 的成员”。 那么如何将Form1实例正确传递给Form2呢?

我还想更改 Form2 中 Form1 的 Button1 的一些属性。 Button1 是在 Private Sub 中声明的,如果我正确传递实例,我仍然能够从 Form2 访问它吗?如果没有,我可以在 Form1 中声明一个 sub,例如

Public Shared Sub ChangeText(newtext As Sting)
 Me.Button1.Text=newtext
End Sub

能胜任吗?

我不是 100% 确定您要实现的目标,但是,您可以在表单之间传递数据。因此,例如,您可以执行以下操作:

Public Class Form1
   Private Sub Button1_click(...) Handles Button1.Click
      Dim newForm2 as New Form2()
      newForm2.stringText = ""
      If newForm2.ShowDialog() = DialogResult.OK Then
         Button1.Text = newForm2.stringText
      End If
   End Sub
End Class

在 Form2 中你有

Public Class Form2
   Dim stringText as string

   Private Sub changeStringText()
      'your method to change your data
      Me.DialogResult = DialogResult.OK 'this will close form2
   End Sub
   
End Class

我希望这是你需要的,如果没有请告诉我

感谢您的回答和评论。所以我为父窗体声明了错误的 class,这意味着在 Form2 中它需要是“parentform as Form1”:

Public Sub New(parentform As Form1)
 InitializeComponents()
 MessageBox.Show(parentform.Button1.Text)
End Sub

是的,我需要跳过 ChangeText 中的“共享”:

Public Sub ChangeText(newtext As Sting)
 Me.Button1.Text=newtext
End Sub

这种方式对我有用。