Home » Microsoft Technologies

Create Session Variables in VB2008


Please am stock in a program.

I am using Windows Forms in VB 2008.
I have a login Form, Form2 and 2 tables (login and clientLogin).
I want to authenticate a user to gain access to other windows forms if the username & password provided are in the login table.
At the same time, I want to record a timeStamp of the login in the clientLoginn table.
Also, based on the provided username n password, I want to SELECT the Firstname field of the login table, store it in a session variable and use it in another Form2.
So that when i Form 2 opens, a Label will display Name of User: Honesty

I do not have problems with the loginform and the Time Stamp.
I am only having problems with creating the session variable.
If I go to form 2, the firstname does not appear on the label. So, I do not know what it is.
Please kindly help me.

Please find the codes below :

Imports ADODB
Imports Microsoft.SqlServer.Server
Imports System.Data.Odbc.OdbcConnection
Imports System.Data.OleDb.OleDbConnection

Public Class Login
    Inherits System.Windows.Forms.Form

' create connection objects here and the recordset objects

    Private myConncetion As New ADODB.Connection
    Private myRecordset As New ADODB.Recordset
    Private myRecordset2 As New ADODB.Recordset
    Private strSQL As String
   Private HasNotConnected As Boolean = False

    Private Sub Connect()
        If myConncetion.State = HasNotConnected Then
            myConncetion.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\OTP.mdb;"
        End If

    End Sub
    Private Sub validateUser()

        Dim Username As String
        Dim Password As String

        '        users.
        Username = UsernameTextBox.Text
        '       users.
        Password = PasswordTextBox.Text

        Me.Validate() 'validate the form
        For Each ctrl As Control In Me.Controls
            If TypeOf ctrl Is TextBox Then
                Dim txtbox As TextBox = CType(ctrl, TextBox)
                If txtbox.Text.Trim = "" Then 'if trimmed of all leading and trailing spaces, the text is blank in the current textbox then
                    '                         'notify user
                    MessageBox.Show("All entries are required", "Missing Entries", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    '                   Return False 'return false
                End If
            End If
        '       Return True 'return true if all textboxes have entries
    End Sub

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        Dim users As New LoginClass

        Call Connect()
        Dim LogID As String
        Dim dt As Date
        Dim tim As Date
        dt = Now.Date()
        tim = Now.TimeOfDay.Hours & ":" & Now.TimeOfDay.Minutes '& ":" & Now.TimeOfDay.Milliseconds

        Dim username As String '= UsernameTextBox.Text
        Dim password As String '= PasswordTextBox.Text

        If UsernameTextBox.Text = "" Or PasswordTextBox.Text = "" Then
            MessageBox.Show("Please do not leave any field empty")
            UsernameTextBox.Text = ""
            PasswordTextBox.Text = ""
            username = UsernameTextBox.Text
            password = PasswordTextBox.Text

' create a session variable called firstname
            Dim firstname As String = "" 

'open the recordset and retrieve all fields where condition specified is met
            myRecordset.Open("Select * From Login Where Username='" & username & "' And UserCode='" & password & "'", myConncetion, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockReadOnly)

' store the firstnameField's value in the firstname session variable
            firstname = (myRecordset.Fields("FirstName").Value).ToString().ToUpper

' this is another string variable that stores the loginId field of the login table
' the LogID variable will be used for an insert statement in the time stamp table.
            LogID = (myRecordset.Fields("LoginID").Value).ToString().ToUpper

' open another recordset for insert statement
' this table is a ClientLogin table used for recording time stamps of a user's login.
            myRecordset2.Open("Select LoginID, LoginDate, LoginTime From ClientLogin", myConncetion, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic)

' note that, in VB6.0, recordset does not make use of .value paremater
' but it does in VB 2008.
'without the .value parameter, it will report an error.
            If (username = myRecordset.Fields("Username").Value) And (password = myRecordset("UserCode").Value) Then

' perform the add new record parameter of the recordset2
                With myRecordset2
                    .Fields("LoginID").Value = LogID
                    .Fields("LoginDate").Value = dt
                    .Fields("LoginTime").Value = tim
                End With

' execute an insert statement into ClientLogin table.
                strSQL = "INSERT INTO ClientLogin (LoginID, LoginDate, LoginTime) VALUES ('" & LogID & "', '" & dt & "', '" & tim & "')"

'since the original operation presented to the user is Login, the messagebox will only show login success
' and will not let the user know that there is a time stamp created during the login session.
' the message to notify the user of a successful time stamp created is deliberately avoided for security reasons on the part of the user.

                MessageBox.Show("Login Successful")

' the login window closes after the OK button is clicked on the messagebox response dialog.

' a notify error message will popup if the login details do not correspond to the information in the database.
                MessageBox.Show("The Username or Password is incorrect. Please try again.")
                UsernameTextBox.Text = ""
                PasswordTextBox.Text = ""
            End If
        End If
    End Sub

Then in form 2, I will have

' Remember our session variable in LoginForm called 'firstname'?
Dim userlabel As String = ""
userlabel = "Name of User: " & LoginForm.firstname

Help pls.

5 Answers Found


Answer 1

Your "session" variables  would need to be public so that they can be accessed by other Forms. There are a number of ways to do this. For example, Firstname" could be defined as a Public Property of your Login Form. Instead of closing your Login Form you could hide it instead and then refer to the Firstname from your other Forms as LoginForm.Firstname.

Another idea would be to declare a global/public variable in a module and store the session  information there. A public variable in a standard module would available from any Form in your application, without needing to qualify it.


Answer 2

Dear Paul, thank you for your response. But my question is:

'How do you declare a global/public module?


Please consider the following class. I tried to instantiate a class called 'LoginClass'

After which I declared some variables. Yet it did not still work for me.

Please see the class below.


Public Class LoginClass
    Protected m_LoginID As Integer
    Protected m_Username As String
    Protected m_userCode As String
    Private m_FirstName As String
    Private m_LoginDate As Date

    Public Property LoginID() As Integer
            Return m_LoginID
        End Get
        Set(ByVal value As Integer)
            m_LoginID = value
        End Set
    End Property

    Public Property Username() As String
            Return m_Username
        End Get
        Set(ByVal value As String)
            m_Username = value
        End Set
    End Property

    Public Property UserCode() As String
            Return m_userCode
        End Get
        Set(ByVal value As String)
            m_userCode = value
        End Set
    End Property
    Public Property FirstName() As String
            Return m_FirstName
        End Get
        Set(ByVal value As String)
            m_FirstName = value
        End Set
    End Property

    Public Property LoginDate() As Date
            Return m_LoginDate
        End Get
        Set(ByVal value As Date)
            m_LoginDate = value
        End Set
    End Property
End Class


in LoginForm, I called the class thus:


Dim Users As New LoginClass

Dim NameOfUser As String=""

NameOfUser = Users.Firstname


it returned an error message: "Users is first used before it is declared"

Please help me.

I am not competent in the class/module of a thing. I usually design my forms  without classes, now I want to delve into the Modular Programming,

Please help me.




Answer 3

Below using a standard Module (Project...Add Module...Module):

Module Module1

  Public FirstName As String

End Module

...referenced just as FirstName

or using a Form:

Public Class Form1

 Public FirstName As String = ""

End Class

...from the Form Class referenced as Form1.FirstName


Paul ~~~~ Microsoft MVP (Visual Basic)

Answer 4

if am creating the Module, what parameters do I insert in the body of the module?

do I just declare and leave it as you have done?


Please give me more hints...




Answer 5

No parameters required. You could place additional code in the code Module if you wish but it's not required. The fact that FirstName is a Public property is sufficient.

FirstName = (myRecordset.Fields("FirstName").Value).ToString().ToUpper

The value of FirstName will be accessible from all Modules and persist throughout the life of the application.


Paul ~~~~ Microsoft MVP (Visual Basic)


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure