Vb.Net – Accessing text in controls on another form

vb.netvisual studio 2012

I am fairly new to vb.net and would like to be able to access the value (such as .text on a textbox) from another an open form. In my application I open a form from my main form, and when I try to access the text in the controls on the main form I am unable to see the .text value on the control.

I can loop through all controls on the main form just fine, but when I want to see the actual values, all controls are empty. My controls such as text boxes and combo boxes are inside of a tab control and group boxes.

Is there a way to make all .text or values on the open form available from the other open form?

Here is how I am looping through the controls on the main form.

Try

    For Each Tp As TabPage In UserData.UserTabControl.TabPages 

    'Name of Tabcontrol is UserTabcontrol

        For Each gbx As GroupBox In Tp.Controls


            For Each ctrl As Control In gbx.Controls

                    If ctrl.Name = "UserName" Then
                        MsgBox(UserData.UserName.Text) 'Messagebox here is empty
                    End If

            Next ctrl

        Next gbx


    Next Tp


    Me.Close()

Catch ex As Exception
    MsgBox(ex.Message)
End Try

Thanks in advance.
Chris

Best Answer

From the example you've given you already have access to a reference to your Control. Instead of going back to the Form and trying to access that control as a property of the Form you could just cast your reference and call its Text property directly.

If ctrl.Name = "UserName" Then
    MsgBox(DirectCast(ctrl, TextBox).Text) 'Assuming your UserName control is a TextBox
End If
Related Topic