Необходимо убедиться, что элементы TextBox
являются публично видимыми с помощью свойства Modifiers
, чтобы вы могли получить доступ к элементам TextBox
из-за пределов форм.
По умолчанию конструктор Windows Forms назначает модификатор private
(Friend
в Visual Basic) элементам управления контейнера, таким как 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"
Другое (и более гибкое) решение:
С помощью следующего решения вы можете получить и установить значениеэлемент TextBox
также в том случае, если для Modifiers
установлено значение Private
. Решение также более гибкое в случае, если элемент 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