How would I declare a global variable in Visual Basic?

前端 未结 3 1976
逝去的感伤
逝去的感伤 2021-01-04 23:08

I want to create a variable that can be used across multiple forms.

It\'s going to be a temporary storage place for integers.

相关标签:
3条回答
  • 2021-01-04 23:24

    IN VB6 just declare on top code

    public GlobalVariable as string
    

    then you can use GlobalVariable in any form as you like.

    like

    GlobalVariable = "house"
    

    then you can use /call in other form

    text1 = GlobalVariable
    

    will show value "house"

    0 讨论(0)
  • 2021-01-04 23:25

    You can just add it as PUBLIC to ANY Module

    Example:

    Module Module1 'Global variables Public glbtxtTemplateName As String 'GLOBAL VARIABLE FOR TEMPLATE

    VB loads the Modals first as a class and all PUBLIC items therein are shared directly. Think about it this way.

    Lets say we have a MODULE called "MY_PROCESSES"

    When you declare a SUB or a FUNCTION in "MY_PROCESSES" if you want it to be used OUTSIDE of "MY_PROCESSES" you declare as PUBLIC like this

    PUBLIC SUB LOAD_TEMPLATE() ....

    To get to LOAD_TEMPLATE you just call it in your code from anywhere:

    LOAD_TEMPLATE

    So if I need to set or use the global variable that I made public in my module I just refer to it by name:

    glbtxtTemplateName="TEMPLATE_NAME"

    IF glbtxtTemplateName="" then LoadTemplate

    I do like building the class as above because you can reference it faster without remembering the variable but if you only need 1 or 2 global variables you can name them like we used to with Hungarian Notation style name. This method is really quite simple and elegant. Old is new and New is Old.

    0 讨论(0)
  • 2021-01-04 23:42

    There are a couple of ways to do this in VB: a VB-specific way and a non-VB specific way (i.e. one that could also be implemented in C#.

    The VB-specific way is to create a module and place the variable in the module:

    Public Module GlobalVariables
       Public MyGlobalString As String
    End Module
    

    The non-VB-specific way is to create a class with shared properties:

    Public Class GlobalVariables
      Public Shared Property MyGlobalString As String
    End Class
    

    The primary difference between the two approaches is how you access the global variables.

    Assuming you are using the same namespace throughout, the VB-specific way allows you to access the variable without a class qualifier:

    MyGlobalString = "Test"
    

    For the non-VB-specific way, you must prefix the global variable with the class:

    GlobalVariables.MyGlobalString = "Test"
    

    Although it is more verbose, I strongly recommend the non-VB-specific way because if you ever want to transition your code or skillset to C#, the VB-specific way is not portable.

    0 讨论(0)
提交回复
热议问题