简体   繁体   English

Visual Basic 如何在切换窗体时设置变量的值

[英]Visual Basic How can I set the value of an variable when switching forms

Basically what the title says基本上是标题所说的

I have several Buttons which redirect me to a 2nd form using me.Hide and Form2.show我有几个按钮使用 me.Hide 和 Form2.show 将我重定向到第二个表单

However, what I would like is that when Button1 is clicked, x=1 in the recently opened form.但是,我想要的是,当单击 Button1 时,最近打开的表单中的 x=1。 When Button2 is clicked -> x=2, etc.单击 Button2 时 -> x=2 等。

Does anyone know how to do this?有谁知道如何做到这一点?

An alternative method is to pass a variable into the constructor of a form, such as:另一种方法是将变量传递给表单的构造函数,例如:

Public Class Form2

    Dim_value As Integer
    Public Sub New(ByVal value As Integer)
        _value = value
    End Sub

End Class

Which you would call like this:你会这样称呼它:

Dim f As New Form2(12345)
f.Show()

You can then use _value (or whatever you want to call it) throughout Form2.然后,您可以在整个 Form2 中使用_value (或任何您想调用的名称)。

The difference here is this is that your value cannot be changed by any other form once Form2 is instantiated;这里的区别在于,一旦 Form2 被实例化,您的值就不能被任何其他表单更改; this may be an advantage or disadvantage depending on your requirements but it does keep things nicely separated and easier to maintain.根据您的要求,这可能是一个优势或劣势,但它确实使事情很好地分开并且更易于维护。 You could also make _value a read-only property which will let others forms read the value but not set (change) it.您还可以使_value成为只读属性,这将让其他表单读取该值但不设置(更改)它。

There are several ways you can do this, but for the sake of simplicity I suggest that you define and use a public method in Form2.有几种方法可以做到这一点,但为了简单起见,我建议您在 Form2 中定义和使用公共方法。 Here's a small example which you can use for inspiration:这是一个小示例,您可以从中获得灵感:

Public Class Form2
    Private variableX As Integer = 0

    Public Sub SetVariableX(value As Integer)
        variableX = value
    End Sub
End Class

and when you reveal Form2:当您显示 Form2 时:

Form2.show
Form2.SetVariableX(9999)

Have fun.玩得开心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM