为什么列表在执行第二个事件时返回空

时间:2017-01-25 16:26:23

标签: c# asp.net list

为什么List在执行第二个事件时返回空?

List<string> ErrorList = new List<string>();

protected void Page_Load(object sender, EventArgs e){}

protected void btnFirst_Click(object sender, EventArgs e)
{
   for (int i = 0; i < 5; i++)
       {
          ErrorList.Add(i);      
       }
   txtResult.Text = "Length of list: " + ErrorList.Count; 
 }

protected void btnSecond_Click(object sender, EventArgs e)
{
   txtResult.Text = "Length of list: " + ErrorList.Count; 
 }
  

点击btnFirst:txtResult.Text =&#34;列表长度:5&#34;

     

点击btnSecond:txtResult.Text =&#34;列表长度:0&#34;

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,但只有在客户端启用了Cookie时才能使用此代码 会话是位于服务器端的容器。在客户端(浏览器)上的cookie是与会话建立关系的id。也可以在cookie中保存更多信息,但我不推荐它。所有其他信息信息都会在每次请求时丢失。

protected void Page_Load(object sender, EventArgs e){}

protected void btnFirst_Click(object sender, EventArgs e)
{
   List<string> ErrorList = new List<string>();

   for (int i = 0; i < 5; i++)
   {
        ErrorList.Add(i);      
   }
   Session["Errors"] = ErrorList;
   txtResult.Text = "Length of list: " + ErrorList.Count;
 }

protected void btnSecond_Click(object sender, EventArgs e)
{
   List<string> ErrorList = (List<string>)Session["Errors"];
   txtResult.Text = "Length of list: " + ErrorList.Count; 
}