Link to home
Start Free TrialLog in
Avatar of tangteng78
tangteng78Flag for Malaysia

asked on

How do I define a global/public variable in ASP.net?

Hi,
I have a public variable which i want it to be updated when user access the page first time, and i use "If Not Page.IsPostBack" to set it. This works fine.

However, i still want to retain this variabe on postback,,,,how can i do it? The public variable always reverted to it's default value that i set during declaration on postback.

See code below for the details.
Partial Class _Default
    Inherits System.Web.UI.Page
 
    Public strTest As String = "This is default setting"
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 
        If Not Page.IsPostBack Then
            strTest = "First time login"
            Response.Write(strTest)
        Else
            Response.Write(strTest)   'I can NOT get the variable to be updated with "First time login" on postback
        End If
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can also use the session-variables

How To Declare and Use Global Variables in your ASP.Net Web Application
http://www.devasp.net/net/articles/display/323.html

How do I store global variables?
http://steveorr.net/faq/GlobalVariables.aspx
Or create a module
' MODULE
Public Module MyModule
 
    Public def As String = "456"
 
End Module
 
 
' PAGE
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.Write(def)
    End Sub

Open in new window