Entry
Visual Basic .net: Variable: Static: ASP.NET: How create variables which retain their values?
Dec 22nd, 2003 14:18
Knud van Eeden,
----------------------------------------------------------------------
--- Knud van Eeden --- 22 December 2003 - 11:15 pm -------------------
Visual Basic .net: Variable: Static: ASP.NET: How create variables
which retain their values?
---
As variables seemingly are not retained between page loads, you should
put your global variables in the file:
global.asax
---
---
Steps: Overview:
1. -Open the file
global.asax
2. -Add the declaration of
your variable at the top of the file
(and make sure your put it in the class 'Global')
Public Shared <your variablename> As <your variable type>
---
e.g.
Public Shared I As Integer
---
3. -Open the file (e.g. webform1.aspx.vb) in which you want to use
this variable
4. -To get the value of this variable in your program, use
Global.<your variable name>
e.g.
Global.I
---
---
Steps: Worked out:
1. -Open the file
global.asax
2. -Add the declaration of
your variable at the top of the file
(but make sure you add this in the 'Class Global')
Public Shared I As Integer
3. -Open the file (e.g. webform1.aspx.vb) in which you want to use
this variable
4. -Put a button on this form
5. -Double click on the button
6. -Fill in the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Global.rowI = Global.rowI + 1
Response.Write(Global.rowI.ToString)
End Sub
7. -Run the application.
8. -It will or should now show the number
1
2
3
...
(so an increasing number each time you click on a button)
---
---
THIS BELOW DOES NOT WORK AS EXPECTED, THE VARIABLE VALUE IS *NOT*
RETAINED WHEN YOU CLICK ON THE BUTTON, IT WILL ALWAYS SHOW
THE NUMBER 1 (as it is all the time initialized to 0 when
you click on the button, after which 1 is added)w
---
Steps: Overview:
1. -Open a Microsoft Visual Studio Visual Basic ASP.NET application
2. -Put a button on the form
3. -Double click on the button, and add the following text in between:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Static I As Integer
I = I + 1
Response.Write( I.ToString )
End Sub
4. -Run this application
5. -When you repeatedly click on the button it will
not increase the number, so continuously show
the following number:
1
...
6. So it keeps the same value between procedure and function calls
---
---
Book: see also:
---
[book: Utley, Craig - a programmer's introduction to Visual Basic.NET -
ISBN 0-672-32203-X - p. 55 'Static not supported on subs or
functions']
----------------------------------------------------------------------