VB.NET массив форм - PullRequest
       7

VB.NET массив форм

0 голосов
/ 03 октября 2019

Предположим, у меня есть три формы: Form0, Form1 и Form2. КАЖДАЯ из форм содержит два текстовых поля: Tb0 и Tb1.

В других формах больше ничего нет. Формы отличаются только фактическим текстом в каждом из текстовых полей (и, разумеется, «именами» отдельных форм).

Формы содержатся в массиве с именем FORMS, т. Е.

  FORMS = {Form0,Form1,Form2}

Я хотел бы получить доступ (для чтения и записи) к первому текстовому полю (Tb0) в форме Form1. Я ожидаю, что смогу сделать это через

 StringVariable = FORMS(1).Tb0.text   or    FORMS(1).Tb0.text = "some string"

, но никакие варианты вышеупомянутого подхода не приводят ни к чему, кроме ошибок. Два дня "поиска в Google" были бесплодными. Предложения ??

1 Ответ

0 голосов
/ 04 октября 2019

Необходимо убедиться, что элементы 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...