Error while using "State Bags".

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi:

The following ASP.NET code segment throws an "Object reference not set to an
instance of an object" exception.
------------------
Public Sub Page_Load(Source As Object, E As EventArgs)

Dim viewCount As Integer

If ViewState("viewCount").ToString() = "" Then
viewCount = 1
Else
viewCount = CType(ViewState("viewCount"), Integer) + 1
End If
labelViews.Text = "Times page has been viewed: " & viewCount.ToString()

ViewState("viewCount") = viewCount
 
Hi,

Perhaps the Viewstate("viewCount") is null. Try this; (Syntax might be
different, I'm not very fluent in VB)


Public Sub Page_Load(Source As Object, E As EventArgs)

Dim viewCount As Integer

If ViewState("viewCount") = Nothing Then
viewCount = 1
Else
viewCount = CType(ViewState("viewCount"), Integer) + 1
End If
labelViews.Text = "Times page has been viewed: " & viewCount.ToString()
ViewState("viewCount") = viewCount


I would also recommend to put

ViewState("viewCount") = viewCount

in the PreRender event instead of Page_Load, since this is the last event
called before the page renders and which eventually will have the latest
value of viewCount.


Hope this helps,

Ethem Azun
 
Thanks! That did work. The value was null.

Ethem Azun said:
Hi,

Perhaps the Viewstate("viewCount") is null. Try this; (Syntax might be
different, I'm not very fluent in VB)


Public Sub Page_Load(Source As Object, E As EventArgs)

Dim viewCount As Integer

If ViewState("viewCount") = Nothing Then
viewCount = 1
Else
viewCount = CType(ViewState("viewCount"), Integer) + 1
End If
labelViews.Text = "Times page has been viewed: " & viewCount.ToString()
ViewState("viewCount") = viewCount


I would also recommend to put

ViewState("viewCount") = viewCount

in the PreRender event instead of Page_Load, since this is the last event
called before the page renders and which eventually will have the latest
value of viewCount.


Hope this helps,

Ethem Azun
 
By the way, ViewState is not the right place to have an application wide
view counter on the page. ViewState is only defined per connection on the
page level.

I would recommend keeping this information either on application level, or
on another persistent datasource like a database (especially if you have many
pages that you want to show this info about.)

Ethem
 
Thanks:

With this source code I was trying to understand State Bags. The actual
purpose was not to implement a page counter.

All that I did was to understand how a key could be added to the ViewState
Property collection such that the value is persisted along with all other
server controls on the page.
 
Back
Top