gpt4 book ai didi

C# 事件 : not firing after second level

转载 作者:行者123 更新时间:2023-11-30 12:47:16 26 4
gpt4 key购买 nike

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

最佳答案

ASP.NET 在每次请求时重新创建整个控件树。您在 .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 网络表单中的动态控件很难。您需要手动跟踪添加了哪些控件,并在每个后续请求开始时重新创建它们。 ASP.NET 不会为您记住这一点。

关于C# 事件 : not firing after second level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17468542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com