使用VB将一个用户控件中存在的值传递给另一个用户控件

使用VB将一个用户控件中存在的值传递给另一个用户控件

问题描述:

我有一个带有文本框的用户控件,我需要访问另一个用户控件中存在的标签中在此文本框中输入的值。

i have a user control with a text box and i need to access the value entered in this text box in a label present in another user control. How do i do that in vb.Thanks in advance.

在第一个用户控件(UserControl1)中创建一个共享事件:

create a shared event in the first user control (UserControl1):

Friend Shared Event GetTextBoxText(ByVal myString As String)

然后可以使用(UserControl1)上的按钮引发此事件

you can then raise this event with a button on (UserControl1)

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

    'raise the event with the text from the text box
    RaiseEvent GetTextBoxText(TextBox1.Text)

End Sub

在第二个用户控件(UserControl2)上添加处理程序构造函数中的事件:

on your second user control (UserControl2) add a handler to the event in your Constructor :

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    'this will let us handle the event from (UserControl1)
    AddHandler UserControl1.GetTextBoxText, AddressOf SetLabelText

End Sub

Private Sub SetLabelText(ByVal myString As String)
    Label1.Text = myString
End Sub

现在,只要您单击(UserControl1)上的按钮,该文本就会显示在UserControl2的标签上

now whenever you click the button on (UserControl1) the text will be displayed in the label on UserControl2

您还可以在任何控件上添加事件处理程序并进行响应GetTextBoxText事件

you could also add the event handler on any control and respond to GetTextBoxText event