How to increment variable when clicking on button.

  • Thread starter Thread starter Ramez T. Mina
  • Start date Start date
R

Ramez T. Mina

I tried to increment variable when I click on a button, but it didn't work.
I use the VB.NET editor and not the HTML editor.

any one can help??
 
You probably faced that the variable showed all the time the same value.
ASp.NET Page class is recreated for every request and therefore normal
members do not persist over the postbacks. You'd need to ViewState to
persist values between postbacks. Example:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim intValue As Integer = 0
If Not ViewState("intValue") Is Nothing Then
intValue = CInt(ViewState("intValue"))
End If
intValue += 1
ViewState("intValue") = intValue

Response.Write("Value of the variable is:" & intValue.ToString())
End Sub
 
in addition to Teemu replay:

viewstate will persist your value using hidden viewstate field
(__VIEWSTATE). the good thing that if you in load balancing environment
this value will reach every server. the bad thing is that you add weight
to your page. you can also use Session object to store your value. using
session you wont send nothing over the web and you can change default
session storage (via wen.config) so session data can be share between
machines in cluster.though hurting performance a little bit

by the way the best way is to implement MVC design pattern and to save
your "state" data in one of model classes.



Natty Gur[MVP]

blog : http://weblogs.asp.net/ngur
Mobile: +972-(0)58-888377
 
Back
Top