我搜索并尝试过很多东西,但是我无法使用以下代码。似乎当我在c#中有三个按钮时,如果我点击第一个按钮它会正确触发。但是,当我单击第二个按钮时,它无法加载第三个按钮。回到第一个。由于某些原因,事件似乎没有超过第一级。提前感谢您的帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
public partial class testingSandbox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
boot();
}
public void boot()
{
firstFunc();
}
public void firstFunc()
{
Debug.WriteLine("func1");
Button btn1 = new Button();
btn1.Text = "btn1";
btn1.ID = "btn1";
btn1.Click += new EventHandler(secFunc);
form1.Controls.Add(btn1);
}
public void secFunc(object sender, EventArgs e)
{
Debug.WriteLine("func2");
Button btn2 = new Button();
btn2.Text = "btn2";
btn2.ID = "b2";
btn2.Click += new EventHandler(thirdFunc);
form1.Controls.Add(btn2);
Button btn1 = (Button)this.FindControl("btn1");
//btn1.Click-=new EventHandler(secFunc);
}
public void thirdFunc(object sender, EventArgs e)
{
Debug.WriteLine("func3");
Button btn3 = new Button();
btn3.Text = "btn3";
btn3.ID = "b3";
btn3.Click += new EventHandler(fourthFunc);
form1.Controls.Add(btn3);
}
public void fourthFunc(object sender, EventArgs e)
{
Debug.WriteLine("func4");
Button btn4 = new Button();
btn4.Text = "btn4";
form1.Controls.Add(btn4);
}
}
答案 0 :(得分:1)
ASP.NET在每个请求上重新创建ENTIRE控制树。您在.ascx文件中编写的内容将被转换为C#代码文件(您可以在ASP.NET Temporary Files
文件夹中找到它)来创建控件,并且该代码在每个请求上运行。但是,在您的情况下,会发生这种情况:
Request 1:
You start out with Button1.
Request 2:
You start out with Button1. A click event for it is received and processed.
In the event handler you add Button2. You end up with Button1 and Button2.
Request 3:
You start out with Button1. A click event for Button2 is received.
Unfortunately there is no Button2, since the control tree got recreated.
The event is ignored. You end up with just Button1.
ASP.NET webforms中的动态控件很难。您需要手动跟踪添加的控件,并在每个后续请求的开头重新创建它们。 ASP.NET不会为你记住这一点。