Search code examples
vb.nettaskform-control

vb .net access form controls in a task


i am trying to access data from textboxes and checkboxes placed on form1 in a task running on form2.

When i access the textboxes and checkboxes within a task started in a sub of form1 everything works fine! But if i try to use the data from the controls in a task of form2 i only get the default text (empty) of the textbox and the default checked status

The following testsub works on form1 and the right text is shown.

Public Sub testsub()
    Dim testTask As New Task(Sub() MsgBox(TextBox1.Text))
    testTask.Start()
End Sub

On form2 i tried this

Public Sub testsub()
    Dim testTask As New Task(Sub() MsgBox(Form1.TextBox1.Text))
    testTask.Start()
End Sub

This doesn't work and only an empty textbox is shown. It seems that the standard instance of the form1 is not available in the task of form2?! Is that right?

So how can i access the control data of form1 in the task of form2?


Solution

  • You need your instance of Form1 declared in a place Form2 can access it.

    Try adding a module :

    Module Mod1
        Public f1 as Form1
    
    End Module
    

    Then in the Form1 Load event, set f1 to the instance of Form1

    f1 = Me
    

    After Form1 has been loaded, then in Form2 you can use your sub, replacing the general Form1 with the specific f1

    Public Sub testsub()
        Dim testTask As New Task(Sub() MsgBox(f1.TextBox1.Text))
        testTask.Start()
    End Sub