Search code examples
.netvb.netwinformsuser-controlsglobal-variables

How to Implement Environment Variables from Login in Visual Basic Across Multiple Forms?


I'm working on a Visual Basic project where I need to implement environment variables set during login and access them across different forms. The idea is to maintain user-specific information throughout the application.

enter image description here

Public Class GlobalVariables
    Public Shared LoggedInStudentID As String
End Class

Despite setting LoggedInStudentID in the login form, I'm encountering difficulties accessing it in the StudentDashboard form. I'm seeking advice on the best approach to share data between forms in Visual Basic.

I've verified that the LoggedInStudentID is set correctly in the login form. However, when attempting to access it in the StudentDashboard form, it appears to be null or empty.

I have been using visual studio 2022 Any insights or examples on how to properly share and access global variables across forms in a Visual Basic application would be greatly appreciated. Thank you!


Solution

  • In a separate code page (e.g., GlobalVariables.vb), add your class like this:

    Public NotInheritable Class GlobalVariables
        
        Private Sub New()
        End Sub
    
        Public Shared Property LoggedInStudentID As String
    
    End Class
    

    Don't bury a Public Class within another Public Class (i.e., your Form class), as it will make it harder for another developer to find and debug your code.

    Now you should be able to Get or Set the student ID anywhere in your application:

    GlobalVariables.LoggedInStudentID = "abc123"
    
    TextBox1.Text = GlobalVariables.LoggedInStudentID