Passing Variables Between Forms

  • Thread starter Thread starter Jim Bayers
  • Start date Start date
J

Jim Bayers

This works and preserves tourID even after a postback:

dim tourID as integer
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then

tourID = Me.Context.Items.Item("id")
Me.ViewState.Add("id", tourID)
Else
tourID = Me.ViewState.Item("id")
End If
End Sub


Why doesn't this work? It seems like it ought to but when you post
back, you lose the variable tourID.


dim tourID as integer
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not Page.IsPostBack Then

tourID = Me.Context.Items.Item("id")
End If
End Sub

Is there a better way to pass variables between forms?
 
No, it shouldn't. The Context collection is there only for the lifetimes of
the request. When the form posts back, this is a different request then that
which originally generated the page.

The behavior you are seeing is exactly what should happen.

ViewState and Session are 2 of the typical ways of preserving variables
between posts. If you google around you will no doubt find many discussions
on the pros and cons of each.
 
Back
Top