如何在 Visual Basic 中跨多个窗体实现登录环境变量?

问题描述 投票:0回答:1

我正在开发一个 Visual Basic 项目,其中我需要实现登录期间设置的环境变量并通过不同的表单访问它们。这个想法是在整个应用程序中维护用户特定的信息。

enter image description here

Public Class GlobalVariables
    Public Shared LoggedInStudentID As String
End Class

尽管在登录表单中设置了 LoggedInStudentID,但我在 StudentDashboard 表单中访问它时遇到了困难。我正在寻求有关在 Visual Basic 中的窗体之间共享数据的最佳方法的建议。

我已验证登录表单中的 LoggedInStudentID 设置正确。但是,当尝试在 StudentDashboard 表单中访问它时,它似乎为 null 或为空。

我一直在使用 Visual Studio 2022 任何关于如何在 Visual Basic 应用程序中跨窗体正确共享和访问全局变量的见解或示例将不胜感激。谢谢!

.net vb.net winforms user-controls global-variables
1个回答
0
投票

在单独的代码页(例如 GlobalVariables.vb)中,添加您的类,如下所示:

Public NotInheritable Class GlobalVariables
    
    Private Sub New()
    End Sub

    Public Shared Property LoggedInStudentID As String

End Class

不要将公共类隐藏在另一个公共类(即您的 Form 类)中,因为这将使其他开发人员更难找到和调试您的代码。

现在您应该能够在应用程序中的任何位置获取或设置学生 ID:

GlobalVariables.LoggedInStudentID = "abc123"

TextBox1.Text = GlobalVariables.LoggedInStudentID
© www.soinside.com 2019 - 2024. All rights reserved.