0

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?

4

2 に答える 2

2

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, the ViewState("SrString") = SrString line 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:

If IsPostBack Then
    'I got this from your comment in the other answer, but I suppose LineNo and FileNameID are comming somehow from the drop downlist, right?
    ViewState("SrString") = "\\...\soi\Bytewise\Line " & LineNo & "\Text Files\" & FileNameID
End If

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/

于 2012-04-19T15:45:35.380 に答える
2

Where is SrString set? From the code you posted, it is only ever assigned to or from the ViewState, and therefore will always be null.

Some more explanation:

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

In page load, we set SrString to the value in the view state.

In your changed event, we set the ViewState to the value of SrString.

However, at no time is SrString ever set to a value, so you're just passing a null value around. There needs to be, somewhere:

SrString = 'some value from somewhere besides the viewstate.

Given:

a=b

b=a

And no other assignment, the value will never change.

于 2012-04-19T15:46:05.770 に答える