www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=133432
I am getting zero for my variable the second time it accesses the subrountine. It is obivous to me that its getting initialized every time, thus reseting it to zero.
How can I initialize the variable once and not have it re-initialized every time? What is the syntax?
Thanks for the help,
-JJust a swag, but are you checking "IsPostBack" in your PageLoad before initializing the variables?
Another thing to remember is that no variables survive a roundtrip to the client. You have to save them somewhere (viewstate, session), and restore their values each time.
I am not sure what you are asking? I am checking for IsPostBack in Page Load, but the variable that is in question is not declared up there, but within the subroutine. When I used to program in PICK it was always good practice to declare your variables at the top of the program and you never had to declare them again. Seems in ASP.NET you, its geared for option explicit, which makes it difficult sometimes when you have to declare everytime you want to use the same variable more than one place in the program.
I did think of this earlier although, but I was getting an undeclared error when I intialized it in the page load.
How do you use the viewstate to handle something like this?
Thanks for you help so far,
-J
In VB.NET or C#.net, you can declare variables at the "class" level. For example:
Public Class MyPage
Inherits System.Web.UI.PageProtected dateBegin As System.DateTime
Protected dateEnd As System.DateTime
etc.
These will be accessable from anywhere in your code-behind, or from the ASPX page that inherits from the code-behind. Typically, then, within a function or sub, you can then use these without declaring them, but they will, of course, need to be initialized first. It is good practice to _only_ use this kind of variable for things that will be needed throughout the class. For variables that are only used within a function, you declare them withing the function. These go out of scope when you exit the function.
Viewstate is pretty simple to use. To store something there:
Viewstate("dateBegin") = dateBegin
To get it back, you need to cast the type:
dateBegin = CType(Viewstate("dateBegin"), System.DateTime)
========
Typically, with your begin/end variables you might do something like:
In page-load:
If Not IsPostBack Then
dateBegin = Date.Today()
dateEnd = dateBegin
Viewstate("dateBegin") = dateBegin
Else
dateBegin = CType(Viewstate("dateBegin"), DateTime)
dateEnd = Date.Today()
End If
Now, if you declared the two dates as "Protected... " at the class level, you can access them in any function that runs after PageLoad in the processing cycle. (and postback handlers DO run after PageLoad).
HTH,
Wow, thank you so much for this explanation. I've also been searching and couldn't find why my variable values where disappearing.
0 comments:
Post a Comment