4

我已经搜索并尝试了很多东西,但我无法让以下代码工作。似乎当我在 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);
}

}

4

1 回答 1

1

ASP.NET 在每个请求上重新创建整个控件树。您在 .ascx 文件中编写的内容将被转换为ASP.NET Temporary Files创建控件的 C# 代码文件(您可以在文件夹中找到它们),并且该代码在每个请求上运行。但是,在您的情况下,会发生这种情况:

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 不会为您记住这一点。

于 2013-07-04T11:43:20.927 回答