您必须确保 TextBox 项目对 Modifiers 属性是公开可见的,以便您可以从表单外部访问 TextBox 项目。
默认情况下,Windows 窗体设计器将private(Visual Basic 中为Friend)修饰符分配给容器控件,如Panel。
现在您可以访问(读取和写入)TextBox,如下所示:
Dim FORMS() As Form = {Form0, Form1, Form2}
'read the value
Dim StringVariable As String = FORMS(1).Tb0.Text
'write the value
FORMS(1).Tb0.Text = "some string"
另一种(更灵活)的解决方案:
如果Modifiers 设置为Private,您也可以通过以下解决方案获取和设置TextBox 项目的值。如果TextBox 项目在Form 上不可用,该解决方案也更加灵活。
'set all the forms to an array.
Dim forms() As Form = {Form1, Form2, Form3}
'search for a specific control on the first form of the array.
Dim foundControls() As Control = forms(0).Controls.Find("TextBox1", True)
'check if the control is available and a TextBox.
If foundControls.Length = 1 AndAlso TypeOf foundControls(0) Is TextBox Then
Dim txtControl As TextBox = DirectCast(foundControls(0), TextBox)
'set a value to the TextBox.
txtControl.Text = "Hello"
'get the value from the TextBox.
Debug.Print(txtControl.Text)
End If
'... or using the functions (much easier to use).
SetTextBoxValue(forms(0), "TextBox1", "Hello World")
Dim strValue As String = GetTextBoxValue(forms(0), "TextBox1")
您可以使用函数更轻松地设置和获取TextBox 项的值:
Private Sub SetTextBoxValue(ByVal frm As Form, ByVal txtName As String, ByVal txtValue As String)
'search for a specific control on the first form of the array.
Dim foundControls() As Control = frm.Controls.Find(txtName, True)
'check if the control is available and a TextBox.
If foundControls.Length = 1 AndAlso TypeOf foundControls(0) Is TextBox Then
Dim txtControl As TextBox = DirectCast(foundControls(0), TextBox)
txtControl.Text = txtValue
End If
End Sub
Private Function GetTextBoxValue(ByVal frm As Form, ByVal txtName As String)
'search for a specific control on the first form of the array.
Dim foundControls() As Control = frm.Controls.Find(txtName, True)
'check if the control is available and a TextBox.
If foundControls.Length = 1 AndAlso TypeOf foundControls(0) Is TextBox Then
Dim txtControl As TextBox = DirectCast(foundControls(0), TextBox)
Return txtControl.Text
End If
Return ""
End Function