dei.andrei98
dei.andrei98

Reputation: 174

How to make a global variable in Visual Basic

I have a Mysql login system in Visual Basic , and I want to store the username in a global variable after a succesful login but when the app will close I want that variable to be deleted.. can you show me some example? I'm a beginner at visual basic.

Upvotes: 0

Views: 13131

Answers (3)

tinstaafl
tinstaafl

Reputation: 6948

Try this, in your form file outside of the main class, or in a separate module file:

Public Module Globals
    Public UserName As String = ""
End Module

Now you can access it in any code throughout your project. It will dispose when the app is closed. If you wanted to make doubly sure, even though it would be redundant, add this to the main form that closes the whole app:

Private Sub Form1_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
    UserName = ""
End Sub

Upvotes: 1

Manny265
Manny265

Reputation: 1709

Just create a class (in your project) that will not be instantiated right...and then have a variable in that class with access modifier Public Shared.
Like for me I made a class called Globals and in it was a variable called currentUser .
So to access the variable from any class I just had Globals.currentUser =txtUser.Text
And declare it like Public Shared currentUser as String

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234665

If you're developing on Windows, then use the Windows Registry to persist the value.

See http://msdn.microsoft.com/en-us/library/aa289494(v=vs.71).aspx for more details, and examples.

Take care if caching a password though; you'll need to encrypt that.

Upvotes: 2

Related Questions