I have the following code to try to use viewstate to save a variable for postback. When post back occurs the SrString value is nothing. I have set the ViewState value at the dropdownlist index chane event and set the variable equal ot ViewState(“SrString”) at page in the if ispostback block.
Can anyone help?
Thanks
'Page Load
If IsPostBack Then
SrString = ViewState("SrString")
End If
'DropDownList Index change event
Protected Sub ByteDataFile_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ByteDataFile.SelectedIndexChanged
ViewState("SrString") = SrString
End Sub
My web config file is correct, because I have other pages in the web site that works with the viewstate fine.
What am I missing?
That is because Page_Load is executed before ByteDataFile_SelectedIndexChanged.
ASP.NET Page life cycle always executes Page_Load first and then it handles events like clicks and SelectedIndexChanged, so when you say
SrString = ViewState("SrString")in Page_Load, theViewState("SrString") = SrStringline hasn’t been called yet.http://msdn.microsoft.com/en-us/library/ms178472.aspx
Assuming you get the value for SrString from dropDownList’s selected item, you just need to get that in Page_Load, something similar to this:
Another thing you need to be sure is that the DropDownList has its AutoPostBack property set to true, otherwise the page won’t postback when you change the selection.
For this kind of thing I think you should use a HiddenField instead of the ViewState.
http://wiki.asp.net/page.aspx/298/hiddenfield/