新建一个ClassLibrary1的工程;在里面添加一个UserControl1的用户控件;控件内有一个按钮UButton1和一个Utextbox1;再添加一个窗体Form1,里面有一个FButton1和一个Ftextbox1;通过UButton1打开Form1,然后在Form1里面,通过点击FButton1 将 Ftextbox1的内容显示到Utextbox1中;通过定义属性的办法;在调试页面可以看到属性值是有的;就是Utextbox1中不显示。
UserControl1中的代码
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frm As New Form1
frm.TextBox1.Text = 2
frm.Show()
End Sub
Public Property tBoxT() As String
Get
Return Me.TextBox1.Text
End Get
Set(value As String)
Me.TextBox1.Text = value
End Set
End Property
Form1中的代码
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'//方法一
Dim uc1 As New UserControl1
' uc1.TextBox1.Text = Me.TextBox1.Text
'//方法二
uc1.tBoxT = Me.TextBox1.Text
End Sub
调试那里,uc1的属性 uc1.tBoxT 已经有值了,但是 uc1的Textbox1 里面就是不显示
你又重新初始化了一个 usercontrol界面,这个界面和之前不是同一个,应该用给之前的usercontrol赋值,你在new form1的时候把usercontrol当参数传进去,在form1里直接给 utext赋值就行了
或者用委托,在form1里定义一个委托,在usercontrol声明事件,这样值就会传到原先的 usercontrol里了
非常感谢jqw2009给的提示。
1-先在form1中定义一个委托 Public SendText As Action(Of String)
2-在form1中的按钮点击事件中,将textbox1进行委托
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SendText.Invoke(Me.TextBox1.Text)
End Sub
3-在UserControl中,建立处理方法
Private Sub Frm_ReceiveText(ByVal txt As String)
Me.Label1.Text = txt
End Sub
4-在UserControl的按钮点击事件中,先实例化委托,再打开form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim frm As New Form1
frm.SendText = New Action(Of String)(AddressOf Frm_ReceiveText)
frm.Show()
End Sub