Asp.net 无法访问的变量代码

Asp.net 无法访问的变量代码,asp.net,vb.net,variables,code-behind,protected,Asp.net,Vb.net,Variables,Code Behind,Protected,这可能是直截了当的 我有一个DropDownList,一旦用户点击一个项目,我需要记住他们在DropDownList反弹之前点击了什么,所以我在外部创建了一个变量 但问题是变量是看不见的。我唯一一次设法让它工作是使用公共共享variableoutside作为整数。但这使它可用于每个页面,我只需要在我运行的页面上使用它 Dim variableoutside as Integer Protected Sub lstTest_DataBound(sender As Object, e As Eve

这可能是直截了当的

我有一个DropDownList,一旦用户点击一个项目,我需要记住他们在DropDownList反弹之前点击了什么,所以我在外部创建了一个变量

但问题是变量是看不见的。我唯一一次设法让它工作是使用公共共享variableoutside作为整数。但这使它可用于每个页面,我只需要在我运行的页面上使用它

Dim variableoutside as Integer

Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
    if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside 
End Sub

Protected Sub lstTest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstTest.SelectedIndexChanged
    variableoutside = lstTest.SelectedIndex
    lstTest.DataValueField = "ID"
    lstTest.DataTextField = "testvalue"
    lstTest.DataSource = List_TestA.List_Test()
    lstTest.DataBind()
End Sub

字段的有效期仅与请求的有效期相同。回发时,您将获得Page类的一个新实例,因此需要新的实例字段

共享(C#中的静态)字段的寿命更长(应用程序的整个生命周期),但它的值在站点的所有用户之间共享-可能不是您想要的

解决方案是将该值存储在中。它是为用户特定值的跨请求存储而设计的。请注意,这些值存储为Object,因此需要转换回Int

编辑
例如,您的代码

Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
    if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside 
End Sub
可能是

Protected Sub lstTest_DataBound(sender As Object, e As EventArgs) Handles lstTest.DataBound
    Dim variableoutside as Integer
    variableoutside = Session("ListIndex") ' probably cast this to Integer
    if variableoutside > 0 Then lstTest.SelectedIndex = variableoutside 
End Sub
(请注意,我猜测的是正确的VB语法,因此您可能需要对此进行调整)

当然,用另一种方法,而不是:

variableoutside = lstTest.SelectedIndex
使用此选项设置该会话值:

Session("ListIndex") = lstTest.SelectedIndex

您可以删除该类字段,因为它不再使用。

哇,这真是太酷了。我喜欢,谢谢你

我稍微改变了一下,把昏暗的房间扔到了外面 并使用会话(“lstest”)作为我的主要变量。它每次都记得

你为我打开了很多扇门,现在我可以用它们来记住很多 下拉列表、复选框、文本框的设置


我唯一想知道的是,您允许使用多少会话变量,因为我假设会话正在使用cookie,并且在开始覆盖会话变量之前,每个客户端和浏览器允许的cookie最大值为。至少在我使用PHP的时候是这样的。

谢谢你的回复,你能详细说明一下我将如何在会话中做到这一点吗,clean版本。