奇怪的VB.net显示其他表单行为的文本

时间:2014-02-09 08:23:15

标签: vb.net winforms

大家好我有这个程序,我想将form1的文本显示到我的form3,其中form2有执行命令的按钮,调试中没有错误但是当我点击我的form2中的按钮时我希望我的form3上的form3上的数据不存在。请提前帮助我们。

Form1代码:

 Public Class Form1
Private frm2 As Form2
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

    If frm2 Is Nothing Then
        frm2 = New Form2
        AddHandler frm2.FormClosed, AddressOf Me.Form2HasBeenClosed

        Dim Label21 As Label = New Label
        frm2.Label21.Text = TextBox1.Text
        frm2.Label21.ForeColor = Color.Black
     End If

    If frm2 IsNot Nothing Then
        frm2.Show(Me) 'Show Second Form  
        Me.Hide()
    End If

End Sub

Form2代码:

Public Class Form2
Private frm1 As New Form1
Private frm3 As Form3
Public lbl As New Label
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    Dim Label21 As Label = New Label
    Dim Textbox1 As TextBox = New TextBox
    frm3.Label21.Text = frm1.TextBox1.Text

        Form3.Show()


End Sub
End Class

1 个答案:

答案 0 :(得分:2)

您需要将Form1实例的引用传递给名为frm2的Form2实例 当您在Form2类代码中尝试显示Form3时,您应该使用该引用来传递Form1的初始实例中存在的值。而是您的代码构建Form1的新实例(Form1 frm = new Form1)并尝试从此实例获取值。当然,作为Form1的新实例,frm1变量不包含原始实例中存在的任何值。

Public Class Form2
    Private frm1 As Form1   ' remove the new here because it creates a new instance of Form1'
    Private frm3 As Form3
    Public lbl As New Label ' not needed?'

    ' add a constructor that receives the instance of the caller'
    Public Sub New(callerInstance as Form1)

        ' Call required if you add your constructor manually'
        InitializeComponent()

        ' save the instance of the Me variable passed to this constructor'
        frm1 = callerInstance
    End Sub

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

       ' Dim Label21 As Label = New Label          ' this label is not needed'
       ' Dim Textbox1 As TextBox = New TextBox     ' this  textbox is not needed'

       ' Create a new instance of Form3, do not use the automatic Form3 instance
       ' automatically created by VB.NET 
       frm3 = new Form3()

       ' now you are referring to the caller instance of Form1 '
       ' where there is the textbox filled with your text '
       frm3.Label21.Text = frm1.TextBox1.Text
       frm3.Show()

     End Sub
End Class

然后更改以这种方式构建Form2实例的Fomr1类中的代码

Private Sub Button3_Click(...........)

    If frm2 Is Nothing Then
        frm2 = New Form2(Me)
        .....

此更改使用Form1(Me)的当前实例调用Form2的类代码中定义的构造函数,并且此实例包含您稍后需要传递给frm3的文本框值。

我不想在这里光顾,但似乎你对类的类和实例有点混淆。您需要非常好地理解这一点,因为它是面向对象编程的基本支柱之一。 (VB自动创建Form对象在这里没有帮助)

这里有一个非常基本的介绍:Classes and Objects