ViewState variable not retaining its value
Hi everybody,
In my web form, I have declared a form level variable - vabc. I am trying to retain the value of the variable after a postback using ViewState. Following is my code:
VB Code:
Dim vabc as String
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Page.IsPostBack Then
vabc = ViewState("vabc")
Else
vabc = "vParty01"
End If
End Sub
Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Unload
ViewState("vabc") = vabc
End Sub
However, after a postback the value stored in ViewState("vabc") is lost. Why is it not retaining the value? What is the solution?
Re: ViewState variable not retaining its value
Page_Unload is not the same in the traditional sense as Windows Forms. The page unload doesn't happen when you close the browser or move to another page. The Page_Unload event happens when the page has finished being processed by ASP.NET, and before it's sent to the browser.
You need to find some other event to set the ViewState on.
Keep in mind, ViewState only saves between page postbacks. If you navigate to another page and back it's lost. For that you need a Session variable.
Re: ViewState variable not retaining its value
Quote:
The Page_Unload event happens when the page has finished being processed by ASP.NET, and before it's sent to the browser.
Do you mean to say that the ViewState variable should be set after the page has been sent to the browser?
Re: ViewState variable not retaining its value
Remove the Page_Unload event.