VB 2008-跨表单调用函数

时间:2013-12-03 10:05:09

标签: vb.net

这是我的计划。

Public Class Form1

    Dim adult As Decimal

    Public Function getadult(ByRef adult As Decimal) As Decimal
        Return adult
    End Function

    Public Function setadult(ByVal value As Decimal) As Decimal
        adult = value
    End Function

    Public Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles adultrate.TextChanged

    End Sub

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

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Form2.Show()
    End Sub

End Class

Public Class Form2

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim adult As Decimal
        Call getadult(adult)
        MsgBox("the rate for adults is " & adult)
    End Sub

End Class

我无法成功调用函数adult及其值为另一种形式。如果我在同一个表单中使用它,它的效果很好。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

最简单的选择是将模块添加到项目中,并将代码放在那里。

你也应该使用一个属性......

Dim _adult As Decimal
Public Property adult As Decimal
    Get
        Return _adult
    End Get
    Set (byval value As Decimal)
        _adult = value
    End Set
End Property

您的两个表单都可以访问此属性。

设置并获取您的财产只需使用;

adult = cdec(adultrate.Text)
adultrate.Text = adult

所以你的代码......

<强> Form1中:

Public Class Form1

    Public Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles adultrate.TextChanged

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        adult = CDec(adultrate.Text)

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Form2.Show()
    End Sub

End Class

<强>窗体2:

Public Class Form2

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox("The rate for adults is " & adult)
    End Sub

End Class

<强>模块:

Module Module1

    Dim _adult As Decimal
    Public Property adult As Decimal
        Get
            Return _adult
        End Get
        Set (byval value As Decimal)
            _adult = value
        End Set
    End Property

End Module

当然,您也可以在模块中使用公共变量.....