C # events: do not shoot after the second level

I searched and tried many things, but I can not get the following code to work. It seems that when I have three buttons in C #, if I press the first one, it will work correctly. However, when I click on the second button, it does not work to load the third button. Returns to the first. For some reason, the events don't seem to go past level one. Thanks in advance for any help.

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
source share
1 answer

ASP.NET recreates the ENTIRE control tree for each request. What you write in the .ascx file is translated into the C # code file (you can find them in the ASP.NET Temporary Files folder), which creates the controls, and this code is run on every request. However, in your case this happens:

 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. 

Dynamic controls in ASP.NET web formats are complex. You need to manually track which controls have been added and recreate them at the beginning of each subsequent request. ASP.NET does not remember this for you.

+1
source

Source: https://habr.com/ru/post/1489682/


All Articles