Visual Basic 2012: Passing variable from one form to another

送分小仙女□ 提交于 2019-12-14 03:00:59

问题


I have two forms, the main (Main.vb) program window and a pop-up that appears when the program is started (getInitialBalance.vb). I need to get a value entered into the PopUp window from the popup window to the Main program. The relevant code is shown below:

getinitialbalance.vb

Public Class GetInitialBalance
    Public initialBalance As Integer

    Private Sub btnApplyInitialBal_Click(sender As Object, e As EventArgs) Handles btnApplyInitialBal.Click
        Dim textinput As Integer = txtInitialBalance.Text
        initialBalance = textinput
        Me.Close()
    End Sub
End Class

Main.vb

Public Class Main
    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        GetInitialBalance.ShowDialog()
    End Sub

    Dim localInitialBalance As Integer = GetInitialBalance.initialBalance

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox(localInitialBalance)
    End Sub
End Class

回答1:


New up the GetInitialBalance form and then when the user clicks OK on the popup dialog, grab the value initialBalance from the reference to GetInitialBalance, like this:

Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim popup As New GetInitialBalance
    If popup.ShowDialog = Windows.Forms.DialogResult.OK Then
        localInitialBalance = popup.initialBalance
    End If
End Sub

Your entire code should look like this:

Public Class GetInitialBalance
    Public initialBalance As Integer

    Private Sub btnApplyInitialBal_Click(sender As Object, e As EventArgs) Handles btnApplyInitialBal.Click
        initialBalance = Convert.ToInt32(textinput)
        Me.DialogResult = Windows.Forms.DialogResult.OK
    End Sub
End Class

Public Class Main
    Dim localInitialBalance As Integer

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim popup As New GetInitialBalance
        If popup.ShowDialog = Windows.Forms.DialogResult.OK Then
            localInitialBalance = popup.initialBalance
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox(localInitialBalance)
    End Sub
End Class


来源:https://stackoverflow.com/questions/20111894/visual-basic-2012-passing-variable-from-one-form-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!