Archive for the ‘Context.Items’ Tag

Context.Items vs. ViewState

To pass values from one page to another, Context.Items and ViewState are used most often.

It is important to keep in mind that values stored in the Context.Items collection only last for the current request. If I were to do a postback on the page, the Context item would be lost. Most of the time this is convienient since we only need to store that value between pages and no longer.

To keep track of values between postback, use ViewState. Unlike Context.Items collection that is used to transfer data from one page to another, ViewState can be only used for the same page. It is useful for postback. Also, Context.Items is used very often in the server farm architecture.

It’s common to use this in the page_load function of the page. Check out the example below. Note that the IsPostBack condition below. If that is not there, then the postback of the page will read Context.Items(“id”) again which will be null. This will cause a problem. That is why it is important to have it there.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ProductToShow As Integer
If Not Me.IsPostBack Then
ProductToShow = Context.Items("Id")
Me.ViewState("Id") = ProductToShow
ProductToShow = Me.ViewState.Item("Id")
End If
End Sub