Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: ASPNET
Expertise: Intermediate
Feb 16, 2002

Saving data between postbacks in the ViewState collection

In classic ASP, the only way to preserve information - for example, the value of a variable- - between consecutive client requests is by means of Session variables, cookies, or other awkward techniques, such as arguments on the query string or values in hidden fields.

ASP.NET gives you yet another method, in the form of the ViewState property of the Page object. (More precisely, this is a protected property that the Page class inherits from the Control class.) This property represents the contents of the __VIEWSTATE hidden field and works as a StateBag dictionary of key-value pairs. The following example uses the ViewState property to preserve the number of requests to the current page:


Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles _
    MyBase.Load

    ' Number of requests to this page posted so far.
    Dim count As Integer
    If Not Me.ViewState("count") Is Nothing Then
        count = CInt(Me.ViewState("count")) + 1
    End If
    ' Store the value back in the ViewState dictionary.
    Me.ViewState("count") = count
    ' Display in a Label control.
    lblCount.Text = count.ToString
End Sub
Keep in mind that this property works only if you left the EnableViewState property set to True.
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date