Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么执行第二个事件时列表返回空_C#_Asp.net_List - Fatal编程技术网

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

C# 为什么执行第二个事件时列表返回空,c#,asp.net,list,C#,Asp.net,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++) { ErrorL

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

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; 
 }
List ErrorList=newlist();
受保护的无效页面加载(对象发送方,事件参数e){}
受保护的无效BTN首次单击(对象发送方,事件参数e)
{
对于(int i=0;i<5;i++)
{
错误列表。添加(i);
}
txtResult.Text=“列表长度:”+ErrorList.Count;
}
受保护的无效BTN第二次单击(对象发送者,事件参数e)
{
txtResult.Text=“列表长度:”+ErrorList.Count;
}
单击btnFirst:txtreult.Text=“列表长度:5”

单击btnSecond:txtResult.Text=“列表长度: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; 
}
受保护的无效页面加载(对象发送方,事件参数e){
受保护的无效BTN首次单击(对象发送方,事件参数e)
{
List ErrorList=新列表();
对于(int i=0;i<5;i++)
{
错误列表。添加(i);
}
会话[“错误”]=错误列表;
txtResult.Text=“列表长度:”+ErrorList.Count;
}
受保护的无效BTN第二次单击(对象发送者,事件参数e)
{
列表错误列表=(列表)会话[“错误”];
txtResult.Text=“列表长度:”+ErrorList.Count;
}

您应该学习和理解,因为页面及其所有变量都是为每个请求新创建的。如上述注释所述,将为每个请求创建新变量。因此,您可以选择将错误列表存储在会话中的选项,这样它将在整个用户会话中保持不变,并且只是一个旁注,不要将
int
值分配给任何语言中
字符串的
数组或
IEnumerable
。即使该语言让您逍遥法外,任何继承您代码的人如果不得不调试任何东西,也会诅咒您的名字
ErrorList.Add(i.ToString())
以防止程序员对程序员的暴力行为。希望您的用户之前不要按btnSecondbtnFirst@SteveBTN秒在用户单击BTN开始后可见。:)有办法保存列表值吗?