I am new to asp.net. I am creating a ASP.net website using VB.net. So here\'s my problem
Dim myCounter as Integer = 0
Protected Sub Button1_Click(ByVal sender A
Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0, for example, will be zero again. This is because the server doesn't know anything about the last time the page ran - all it knows is you clicked a button which submits a form to that page, so it creates another instance of the page and starts again.
If you need to persist a value across postbacks, the standard method is to use ViewState:
Public Property MyCounter() As Integer
Get
Dim val As Object = ViewState("MyCounter")
Return If(val IsNot Nothing, CInt(val), 0)
End Get
Set(ByVal value As Integer)
ViewState("MyCounter") = value
End Set
End Property
It's also possible to use Session, which will persist the value across all pages and requests for the life of the user's session. For that to work, you can use the same sample above, replacing ViewState
with Session
.