Monday, March 26, 2012

Sharing variables across procedures

Hi, I know that this is fairly simple to do, but I can't seem to get it right. I have four sets of variables called holder1, holder2, vid and iid, which are all Integers. I need the variables to hold values given in one sub, and then have those values used in another sub later, but for some reason whenever I move to the next sub the variables get their values reset back to 0.

All of the code is taking place on one page, so i really can't understand why it isn't working.
I have declared the variables as follows:


SHARED DIM iid, vid, numberofrows AS Integer
SHARED DIM Holder1, Holder2 AS Integer

iid = Cint(dS1.Tables("Box").Rows(0).Item(0))
vid = Cint(dS1.Tables("Box").Rows(1).Item(0))

Selector(iid)

Holder1 = 2
Holder2 = 3

Please Help!Simply declare the variables outside the scope of the method (and no need to declare them shared/static):


Dim i As Integer
Dim holder1 As Integer

Public Sub MySub1()
i = 10
End Sub

Public Sub MySub2()
' Over here i is 10
End Sub

Note that every time an ASP.NET page is served the variables will be reset. This is the stateless nature of the Web.
OK, to work around the problem of the page being re-served and all of the variables being emptied, I have chosen to store my values in Session variables, but for some reason the Session variables are also emptied everytime I move to a new sub routine!

Why is this happening? I thought by using session variables I could store any values I wanted to, and have these values shared across the site. At the moment my one sub routine inserts the values that I get from the dataset in Session variables like this:


Session("iid") = Cint(dS1.Tables("Box").Rows(0).Item(0))
Session("vid") = Cint(dS1.Tables("Box").Rows(1).Item(0))

but when I try to get the values out of the session variables they are empty!
What do you mean they are empty? They have null values? How are you accessing the Session objects?
Maybe you forgot to wrap it in a PostBack expression?
ie.

If IsPostBack Then
...
<Set Variables>
...
End If

otherwise your code will be called immediately when the page loads and
your dataset may not have been filled yet?

0 comments:

Post a Comment