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)


I added the following code to global.asax to load up several session variable when a session starts. I'm assuming that when a page goes to use the variable that I should be

1) checking at the page level that the value is valid not 0 when its not expected to be 0, not a zero-length string when its expected to have a length

2) have code at the page level that sets the values if the values have not been set as when the Session timeout, ideally putting the code in a class derived from Page and then deriving all of my pages from the new class so that the code does not have to be repeated in every page

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when a new session is started
        'Move code here that sets the User Session Variables, currently done in the code behind of DefaultDirectory and the Dashboard Masters
        Dim ExceptionMessage As New StringBuilder
        ExceptionMessage.Append("Site accessed using " + Request.Browser.Browser + " " + Request.Browser.MajorVersion.toString + "." + Request.Browser.MinorVersion.tostring)
        Dim NewException As New NotSupportedException(ExceptionMessage.ToString)
        Dim CurrentUser As New MercurySiteUser.SiteUser()
        Session("UserExists") = CurrentUser.Exists
        Session("UserName") = CurrentUser.Name
        Session("UserContactId") = CurrentUser.ContactId
        Session("UserDepartmentId") = CurrentUser.DepartmentId
        Session("UserBranchId") = CurrentUser.BranchId
        Session("UserCompanyFacilityId") = CurrentUser.CompanyFacilityId
        Session("UserAddressCity") = CurrentUser.AddressCity
        Session("UserAddressState") = CurrentUser.AddressState
        Session("UserTimeZoneId") = CurrentUser.TimeZoneId
        Session("UserTimeZoneOffet") = CurrentUser.TimeZoneOffset
        Session("UserDashboardURL") = CurrentUser.DashboardURL
        Session("UserDashboardId") = CurrentUser.DashboardId
    End Sub


hi guys

its a newbie question, i could use Global x as string in vb6 in a module to declare it with global privelages, how can i do this in vb2008? how to declare a global variable in vb2008? so that i could use it anywhere i want. i know global variables are not recommended in programming but i need one.

thanks in advace...

I have written a VBA script in Excel 2007 that automates an application (CATIA V5R18). The VBA script works fine. I now want to make a visual basic 2008 console application that does the same thing, but in Visual Studio 2008, I get an exception saying "Cannot create ActiveX component" when using GetObject(, "CATIA.Application"). By the way, I am using Windows 7 Home Premium 64bit. I also added the necessary reference in Excel and in VS2008 to my application (the Interop.INFITF assembly which contains the INFITF namespace).

I manually start CATIA (double clicking the shortcut) and then start the VBA script.

Excel VBA (works fine, I see the msgbox appear):

Public Sub Main()
    On Error Resume Next
    Dim app As INFITF.Application
    Set app = Interaction.GetObject(, "CATIA.Application")
    If app Is Nothing Then
        Set app = Interaction.CreateObject("CATIA.Application")
    End If
    MsgBox app.Documents.Count
End Sub

CATIA is still open, I then run my console application.
The first time I run this, a "Cannot create ActiveX component" exception is thrown and caught so it creates a new CATIA application! app.visible=true makes the second CATIA application appear (I now have 2 CATIA apps opened)! If I rerun the whole console application, this time, GetObject works! It retrieves the new CATIA, the one it created a few seconds ago and everything is fine. But why can't I retrieve the manually opened application like in Excel VBA?

    Sub Main()
        Dim app As INFITF.Application

            app = Interaction.GetObject(, "CATIA.Application")
            app = Interaction.CreateObject("CATIA.Application")
        End Try
        app.Visible = True
    End Sub

s = initialize_selltab()
t = s
tt = s
AddHandler Button1.Click, AddressOf add_selltab

Sub add_selltab()
    s = s.left
    s = initialize_selltab()
    s.right = tt
    tt = tt.right
End Sub
Now, I've learned in java that t and tt are suppose to point to s only, not duplicate. Does it work differently in VB?

Because it's like tt and t duplicate from s, they don't change when s changed afterward.
PublicClass Selltab
  Public a AsNew ComboBox
  Public b AsNew Button
  Public c AsNew ComboBox
  Public d AsNew ComboBox
  Public e AsNew Label
  Public f AsNew TextBox
  Public g AsNew Label
  Public left As Selltab = NothingPublic right As Selltab = Nothing



My web application is in .net 2.0 and am using ajax tool kit as well.The problem i face is some times the session is getting expired and the user is thrown out of the site.This is not happening always.But as the number of users increased , the error also is coming more now.My session variables are set in login page and I check for these variables in all subsequent pages.I have put this check in the page load of my master page.Can any one help me on this as the issue has become very critical.



I was wondering if it is possible to store session variables in a webpart? I have read a few posts about this, and about how to modify the web.config...

I am storing session variables like this during the webpart's OnUnLoad:  this.Page.Session.Add("Items", this.Items);

then i try to retreive them like this during the webparts OnLoad : this.Page.Session["Items"]


The session variables are empty during the OnLoad. Is it possible that the Session is removed during a webpart's OnUnLoad?


Hi All,

I'm developing an application for Windows Server 2008 R2. In that app I need to share a DWORD value across processes. Currently I use following method.

#pragma data_seg( "shrdsec" )
DWORD g_dwConfigLastUpdateTime = 0;
#pragma data_seg()

#pragma comment( linker, "/section:shrdsec,RWS" )

My program will be used by users in multiple sessions simultaneously. But the sharing of the variable across sessions is not working (Sharing inside a session is working fine). This is a very frequently accessed value so I'm hesitant to use shared memory. Is there any other methods? Or is it okay to use shared memory?

Please give some suggestions.

Thanks and regards,



I’ve read somewhere that we are not supposed to store user session variables in an application developed for Azure, because if multiple instances of a role exists there is no guarantee that subsequent calls will be made to the same role.

Is this correct?



I wanted to know if someone could instruct me on how to create a session variable that I could use as a parameter when filtering a DVWP?  I have a custom form that is attached to a custom list (a new edit form).  I have added a DVWP to the bottom of this form in order to display relevant documents to this record as they are added to the document library.  This DVWP has an upload button that will allow the user to proceed directly to the upload dialog window to upload to the library.  When the user clicks on this button, I need the id of the list record to follow along and populate the GTID field of the library for that document.  This way when a user goes into the list record to either edit the metadata fields or add a document, the rollup in the DVWP will be accurate to this record.

As you can see from the image below, a user will first check off that they are uploading a Board List document and then clicking on Upload they will be directed to the upload dialog of the document library hosting all documents related to this record (and others).  Once the document is upload, then it will appear in the document rollup on teh bottom of the page.

Can anyone help or direct me to some good links on this topic?








This is a pretty basic question.

I have some code where I need to define a session variable  however it's coming back as Nothing when the code is executed. Here's the code:

' Default Currency

REQCURR = Request.Querystring("p_DCURR")
'If not explicitly specified, try to get it from session

If (REQCURR = "") Then

     If (Session("REQCURR") <> "") Then
          REQCURR = Session("REQCURR")

          'Here is the session variable I'm trying to define:
          Session("REQCAD") = 0
          REQCURR = ""
     End If

End If


So, for some reason that Session("REQCAD") = 0 has no value instead of having a value of 0.

Any thoughts?



I have a page with 2 dropdown menus and 2 datagrids.
The datagrids get populated by a database based on a dropdown menu slection.

This page links to another page which in turn links back to the original.
If the user leaves the first page and then returns back I want to keep the dropdown menus and datagrids populated.

I tried doing this with session variables but can't get the datagrids to stay populated ...

    protected void btnSubmit_Click(object sender, EventArgs e)
        if (this.ddlName.SelectedIndex > 0)
            GridView1.Visible = true;
            GridView2.Visible = false;

            Session.Add("name", this.ddlName.SelectedValue);
            Session.Add("gridview1", GridView1.SelectedValue);

    protected void btnSubmit_Click1(object sender, EventArgs e)
        if (this.ddlLocation.SelectedIndex > 0)
            GridView2.Visible = true;
            GridView1.Visible = false;

            Session.Add("location", this.ddlLocation.SelectedValue);
            Session.Add("gridview2", GridView2.SelectedValue);

    protected override void Page_Load(object sender, EventArgs e)

        if (!IsPostBack)
            if (Session["gridview1"] != null)
                GridView1.Visible = true;
                GridView2.Visible = false;

            if (Session["gridview2"] != null)
                GridView2.Visible = true;
                GridView1.Visible = false;



I am using ASP.NET 2.0

I am little bit confuse about using of Session Variable.
I have a three page web application. When a user login, after verification of user credentials I get user ID from DB and store this ID in a session variable.

Session("USERID") = 56

by using this ID I can get 20 different values from database as User Full name, user date of birth, user location, user date of joining, User Commission rate  etc. I need some of these values in Page 1, some in page 2 and some values needed in Page 3

My question is that what is the best method !

01. After successfully login and getting the User ID, I take all these 20 values from Data Base and store these values in an ArrayList and store this ArrayList in a seesion and whenever I need to use any value I take these values from ArrayList which is save in Session variable.

02. I only save the user ID in session variable and whenever needed any user preference data, by using this ID I run the sql query and get the data and use this.

03. Can I take some benefit by using the IsolatedStorage for this purpose.


I have noticed a strange behaviour in my ASP.net 2.0 application.

 I have some logic in my aspx page that accesses some Session variables fine, then accesses some app_code and most of the time the HTTPContext.Current.Session returns the variable back fine.  However, I have noticed that sometimes this Session returns null, like it has lost it's "pointer" to the current HTTPContext.

 Is this a known bug, has anyone seen something like this before?

  Any help would be appreciated, thanks,





Dear All,

In my project i need to set session in an ashx file and access that session in aspx.cs file. for this i am dooing the following things.

In .ashx file

public class Upload : IHttpHandler , System.Web.SessionState.IRequiresSessionState

    public void ProcessRequest(HttpContext context)

            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            context.Session["img"] = postedFile.FileName;



After the file upload happand i wrote the code in .aspx.cs file

protected void Button1_Click(object sender, EventArgs e)

this is working fine in IE but in Mozilla,Chrome,safari and Opera i got Session["img"] is null. Any help can be appreciated

Thanks & Regards
Basheer K M
Cybrosys Technologies Pvt. Ltd.
Calicut. http://www.cybrosys.com


I have a custom class that pulls user information from a SQL Server table. Now that I'm expanding the site from a single page to others. I want to shift the code to the Session_Start event so that the information is always loaded when the site is accessed. How do I call my custom code from global.asax since its script and not a class. 


I was debugging my web project and faced a problem that I don't know how to watch content of hashtables or similar data structures.

For example, I have assigned before that Session["errorMessage"]="Hewstone we have a problem here...". What is my actions in order to watch that string in watches list?


Hey Forumers,

I have been trying to get this javascript to work, but it seems it doesn't display my image.

<script type="text/javascript">
function getAvatar()
    var currentUser = <%=Session("UserName")%>
    $('himg_something').src = "~/ProfileImage/" + currentUser + "/avatar.jpg"


himg_somthing is the img tag as follows:

<img id="himg_something" alt="Avatar" src="~/ProfileImage/Image1.bmp" onload="getAvatar()"/>

What I am basically trying to achieve is to display the user's avatar based on the session variable in code behind, but I cannot seem to get it to work.

Thanks in advance



Hi all,

Is it possible to use a session variable in the markup aspx page ?

Cause I have a gridview that use an sqldatasource and in the UpdateCommand I want to include a the session variable : session("username").

Ex :

UpdateCommand="UPDATE departments SET DEP_name = @DEP_name, DEP_active = @DEP_active, DEP_date_stamp = CONVERT (CHAR(8), GETDATE(), 112) + ' ' + CONVERT (VARCHAR(8), GETDATE(), 108), DEP_user_stamp = <% session("username") %> WHERE (DEP_mnc = @original_DEP_mnc)">

This give me an error :

Server tags cannot contain <% .... %> constructs.


 OK this is what i have.

In my project i have the following folder structures.


where the folder named 2507 corresponds with a "driverid" which is their loginid (session variable named "cid")

i need to set the DataNavigateUrlStringFormat to a path which includes a session variable and i am lost, i have tried <!# <!= with no luck can someone help me get the proper format? All i want to do is list all the files in each users folder.

It displays the correct files in the datagridnames in the datagrid but the link created is wrong.

I need the datanavigateurlstringformat to be  "~/secure/settlements/SESSION("CID")/{0}

Can i even use a session variable in the DataNavigateUrlStringFormat?

Here is my code:


<%@ Page Title="" Language="VB" MasterPageFile="~/Secure/MasterPage.master" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not Page.IsPostBack Then
            Session("Cid") = Nothing
            If User.Identity.IsAuthenticated Then
                If User.IsInRole("Administrators") Then
                    If Request("cid") IsNot Nothing Then
                        Session("Cid") = Request("cid")
                    End If
                    Session("Cid") = User.Identity.Name
                End If
            End If
        End If
        Dim dirInfo As New DirectoryInfo(Server.MapPath("~/secure/settlements/" & Session("cid") & "/")) 
        SettlementList.DataSource = dirInfo.GetFiles("*.pdf")
    End Sub


<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
   <%= Session("cid")%> Just displayed variable for test purposes
   <asp:DataGrid runat="server" id="SettlementList" AutoGenerateColumns="False" 
        Height="127px" Width="674px">
    <asp:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" 
           HeaderText="Settlement Issued" 
          DataNavigateUrlFormatString='~/secure/settlements/' & <%= Session("cid") %> & '/{0}' />



Hi all:

I have a master page and 2 content pages.

In the master page I use a session variable. As it, I suppose this session variable is read by the two content pages.

But it isn't working. This session variable is read by the first content page and not the second.


Thanks in advance if you can help me





<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure