How do I save an object with value, after postback?

  • Thread starter Thread starter Mark Fitzpatrick
  • Start date Start date
M

Mark Fitzpatrick

Every time the page is loaded, the variable is re-created. The page itself
is inherently stateless, but you can save variables into the viewstate of
the page in an attempt to retain their state. Before you fetch anything from
the viewstate, just check to make sure it isn't null for some reason.

if(ViewState["TimeStr"] != null)
{
string temp = ViewState["TimeStr"].ToString();
ViewState["TimeStr"] = (temp + ("<br>" +
System.DateTime.Now.ToString()));
}
else
{
ViewState["TimeStr"] = ("<br>" + System.DateTime.Now.ToString());
}

You'll forgive me if the above code is in C#, but it's been too long since I
worked with VB.


Hope this helps,
Mark Fitzpatrick
Microsoft MVP - FrontPage
 
Hi Leo,

What You are forgetting is that your page object is created and destroyed
with request.
This means that your TimeStr variable is initialized on each postback.

You need to store the vairiable in either ViewState, Session or Application
in order to persist its value.
In this case i would use the viewstate and create persistable property like
this:

Public Property TimeStr()
Get
return ViewState.Item("TimeStr")
End Get

Set(ByVal Value)
ViewState.Item("TimeStr") = Value
End Set
End Property

/ricky
 
I tried to simplify my problem.

What I want to do is to save a string in a variables, and everytime I click
a button, the variable string gets a bit longer by adding the time to it: on
the form there is a button. Somehow the submit seems to initialize the
variable again, rathen then keeping its previous state/value.
The variable has to be public to all methods in the class.

codebehind:

Dim TimeStr As String

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'nothing here
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
TimeStr &= "<br>" & Now().ToString
Response.Write(TimeStr)
End Sub

I guess I am overseeing something basic here. Can anyone help me out?

Thanks,

Leo


--

-----------------------------------------------
Leo Muller ìéàå îéìø
Webmaster Keshet Interactive
(e-mail address removed)
03 - 7676383 / 067 - 972985
--------------------------------------
http://www.keshet-i.com
http://www.mooma.com
http://www.hakasefet.co.il
http://www.bip.co.il
http://www.keshet-tv.com
 
Back
Top