keeping a variable value on postback

D

Darrel

I'm dimming a string at the top of my page so I can use it in several
different subs on the page.

I'm setting the text in one sub and then reading it in several. I'd like to
also use this varable on postback. The catch is, since I'm dimming it at the
top of the page, it resets itself on postback.

The fix I cam up with is to, on page load, populate a hidden field with the
value I want, then read that back on postback. But is there a more
elegant/straightforward way to achieve this?

-Darrel
 
K

Karl Seguin

The viewstate uses a hidden field but is mre "elegant" since its an actual
class you can program against....you can do it as a property:

public property MyValue() as string
get
If (ViewState("myValue") Is Nothing) Then
Return "initialValue"
End If
return cstr(ViewState("myValue"))
end get
set (value as string)
ViewState("myValue") = value
end set
end property

or more straightfowardly:

Sub Page_Load
dim myValue as string
if not page.IsPostBack
myValue = "initialValue"
else
myValue = cstr(ViewState("myValue"))
end if
end sub

Without seeing your code I can't tell you where, in this 2nd example, you
would set the viewstate via ViewState("myValue") = myValue but it should
be the same place you are creating the hidden form field.

Karl
 
K

Ken Dopierala Jr.

Hi Darrel,

You can use the Cache object:

Cache("MyString") = "Test String"

Now, whenever you use Cache("MyString"), it will return the value. If this
is different for each user then use Session() instead of Cache(). One thing
to be aware of is that a Cache("whatever") variable can expire at any time.
So you should always check it for Nothing and re-create it if that happens.
The best way to do this is to encapsulate the Cache object in your own
class. Then use that classes properties and have those properties reference
the Cache object. In those properties test for Nothing and if it Is Nothing
then put the logic in there to re-create it. Good luck! Ken.
 
K

Karl Seguin

Problem with the cache is that it's shared accross multiple requests.
Multiple requests to the same page from multiple users will/could result in
problems.

Karl
 
K

Ken Dopierala Jr.

Hi Karl,

Good point. That is why I recommended using Session if this value would be
different for different users. I like your ViewState example though, don't
have to worry about it expiring or anything. Ken.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top