简体   繁体   中英

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

However, what I would like is that when Button1 is clicked, x=1 in the recently opened form. When Button2 is clicked -> x=2, etc.

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.

The difference here is this is that your value cannot be changed by any other form once Form2 is instantiated; 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.

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. 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.show
Form2.SetVariableX(9999)

Have fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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