我有一个登录表格。当我成功登录后,登录表单关闭(未隐藏),主表单将显示用户信息。如何将用户名临时保存到变量中以便进一步查询?我正在使用用户名以各种形式查询当前用户的信息。从一个窗体跳到另一个窗体时,前一个窗体关闭。因此,以当前形式存储在变量中的用户名消失了。 传递变量不起作用,可能是因为尚未打开其他表单吗?
登录信息
mainform.username = tbUser.text
MainForm
Public Class mainform
Public username as string
...Some codes here
End Class
当我尝试以主要形式向其发送消息时,它什么也没显示
答案 0 :(得分:2)
要能够从所有表单访问用户数据,请创建一个具有Shared属性的类。在您的第一个表单中创建用户。
Public Class User
Friend Sub New()
'Put back the default constructor
End Sub
Friend Sub New(uName As String, uDepartment As String, uAccess As String)
UserName = uName
UserDepartment = uDepartment
AccessLevel = uAccess
End Sub
Friend Shared Property UserName As String
Friend Shared Property UserDepartment As String
Friend Shared Property AccessLevel As String
End Class
在第一个表单上的任意位置创建用户。
Dim LoggedInUser As New User("Mary", "Accounting", "Administrator")
Form2.Show()
Close()
然后以任何其他形式...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show($"The user name is {User.UserName}, their department is {User.UserDepartment}, their Access Level is {User.AccessLevel}.")
End Sub
编辑
从类中删除了构造函数,并添加了Private构造函数。我相信这使该类类似于C#静态类。
Public Class User
'A private constructor prevents instantiation
Private Sub New()
End Sub
Friend Shared Property UserName As String
Friend Shared Property UserDepartment As String
Friend Shared Property AccessLevel As String
End Class
然后在主窗体中直接设置属性
User.UserName = "Mary"
User.UserDepartment = "Accounting"
User.AccessLevel = "Administrator"
Form2.Show()
Close()
其他形式的代码相同。