我有一个存储单词的数组。每次单击按钮时,我需要能够访问一个单词。下次单击该按钮时,我需要能够访问数组中的下一项。
我在vb.net上运行良好,但是在asp.net/vb.net中,每次单击按钮时,我的公共变量都重置为零,因此每次都得到相同的项目。
Partial Class Residential
Inherits System.Web.UI.Page
Public NextNum As Integer
Private Sub ProducePurpleSentence()
Dim calltoactionArray(3) As String
calltoactionArray(0) = "Go!"
calltoactionArray(1) = "Run!"
calltoactionArray(2) = "Jump!"
calltoactionArray(3) = "Yell!"
PurpleSentence = ""
'This should reset NextNum to 0 once the last array element is reached.
If NextNum > calltoactionArray.Length + 1 Then
NextNum = 0
Else
End If
PurpleSentence = calltoactionArray(NextNum)
'NextNum should iterate here.
NextNum = NextNum + 1
TxtOutput.Text = PurpleSentence
End Sub
Private Sub BtnPurpleRedo_Click(sender As Object, e As EventArgs) Handles BtnPurpleRedo.Click
Call ProducePurpleSentence()
End Sub
End Class
第一次单击BtnPurpleRedo时,我需要“ PurpleSentence”作为calltoactionarray的第一个数组元素,第二次单击时,它需要sencond元素,依此类推。一旦输出了最后一个元素,我还需要它返回到第一个元素。
答案 0 :(得分:0)
您可以在“会话状态”下在两次页面调用之间保留数据。 (可以保存它的其他地方,在某些情况下以某些方式更好。)
首先,您必须在web.config中启用会话状态:在<configuration>
元素内添加以下内容:
<system.web>
<sessionState mode="InProc" cookieless="false" timeout="20">
</system.web>
然后您可以使用它来保存变量:
Private Sub ProducePurpleSentence()
Dim calltoactionArray = {"Go!", "Run!", "Jump!", "Yell!"}
Dim nextNum As Integer = 0
If Session("nextNum") IsNot Nothing Then
nextNum = DirectCast(Session("nextNum"), Integer)
End If
Dim PurpleSentence = calltoactionArray(nextNum)
nextNum = (nextNum + 1) Mod calltoactionArray.Length
Session("nextNum") = nextNum
TxtOutput.Text = PurpleSentence
End Sub