如何将数据从一个表单传递到多个表单VB.net

时间:2017-01-02 07:05:28

标签: vb.net forms winforms visual-studio

我的Form1看起来像是为了获取textbox的值以将数据传递给多个表单。:

Public Class Form1

Public username As String

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    username = TextBox1.Text
    Form2.Show()
    Me.Close()
End Sub
End Class

在第二种形式中,我使用此代码显示从Form1输入的用户名数据。:

Public Class Form2

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label1.Text = "Hi " & Form1.username & "!"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Form3.Show()
    Me.Close()
End Sub
End Class

完美无缺。数据以第二种形式出现。但在Form3中,它只显示" Form1"

Form3代码:

Public Class Form3

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Label2.Text = Form1.username
End Sub

如何使用户名的数据显示在多个表单上?

1 个答案:

答案 0 :(得分:0)

不要使用表单的默认实例,为使用username作为参数的表单创建构造函数,然后显式创建表单

Public Class Form3
    Private _username As String
    Public Sub New(username As String)
        _username = username
    End Sub

    Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Label2.Text = _username
    End Sub
End Class

Public Class Form2
    Private _username As String
    Public Sub New(username As String)
        _username = username
    End Sub

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Label1.Text = $"Hi {_username}!"
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim formThree As new Form3(_username)
        formThree.Show()
        Me.Close()
    End Sub
End Class

Public Class Form1
    Private _username As String

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim formThree As new Form3(TextBox1.Text)
        formThree.Show()
        Me.Close()
    End Sub
End Class

使用这种方法,您不需要将用户名公开为Form1的公共属性。