简体   繁体   中英

Vb.Net - Accessing text in controls on another form

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

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

If you would like to reference controls on an open form, call it Form1: First add a Form1 property or variable to the calling form:

Public Class Form2
    Public Property f1 As Form1

    ...
    Private Sub DoSomething()
        MsgBox("Here's some text from Form1: " & f1.Textbox1.Text)
    End Sub
End Class

In the callee form, set the Form2 property to the form object:

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
       Form2.f1 = Me
       Form2.ShowDialog() ' or Form2.Show()
    End Sub
End Class

You can then reference all Form1 objects from Form2 using the f1 property.

By this command, I could change the amount of control in another form.

My.Forms.myForm.labelControl.Text = "bela"

Please try this :

MsgBox(My.Forms.UserData.UserName.Text) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM